Bug 1471629 - [wpt] Update pytest to version 3.6.2. draft
authorHenrik Skupin <mail@hskupin.info>
Thu, 28 Jun 2018 09:40:32 +0200
changeset 811776 815b8f7d78cebcec3058a9ef514349315c03d508
parent 811775 4bb930e8212083307ce90380b9ec21c6e1938b05
child 811777 899227105ef93546bd9f80393dbc7bb129e506db
push id114419
push userbmo:hskupin@gmail.com
push dateThu, 28 Jun 2018 08:51:00 +0000
bugs1471629
milestone63.0a1
Bug 1471629 - [wpt] Update pytest to version 3.6.2. MozReview-Commit-ID: JY1T0T7W4Ex
testing/web-platform/tests/tools/localpaths.py
testing/web-platform/tests/tools/third_party/pytest/.coveragerc
testing/web-platform/tests/tools/third_party/pytest/.github/PULL_REQUEST_TEMPLATE.md
testing/web-platform/tests/tools/third_party/pytest/.gitignore
testing/web-platform/tests/tools/third_party/pytest/.pre-commit-config.yaml
testing/web-platform/tests/tools/third_party/pytest/.travis.yml
testing/web-platform/tests/tools/third_party/pytest/AUTHORS
testing/web-platform/tests/tools/third_party/pytest/CHANGELOG.rst
testing/web-platform/tests/tools/third_party/pytest/CONTRIBUTING.rst
testing/web-platform/tests/tools/third_party/pytest/HOWTORELEASE.rst
testing/web-platform/tests/tools/third_party/pytest/README.rst
testing/web-platform/tests/tools/third_party/pytest/_pytest/__init__.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/_argcomplete.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/_code/__init__.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/_code/_py2traceback.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/_code/code.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/_code/source.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/assertion/__init__.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/assertion/rewrite.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/assertion/truncate.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/assertion/util.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/cacheprovider.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/capture.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/compat.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/config.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/debugging.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/deprecated.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/doctest.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/fixtures.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/freeze_support.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/helpconfig.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/hookspec.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/junitxml.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/logging.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/main.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/mark.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/monkeypatch.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/nodes.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/nose.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/outcomes.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/pastebin.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/pytester.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/python.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/python_api.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/recwarn.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/resultlog.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/runner.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/setuponly.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/setupplan.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/skipping.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/terminal.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/tmpdir.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/unittest.py
testing/web-platform/tests/tools/third_party/pytest/_pytest/warnings.py
testing/web-platform/tests/tools/third_party/pytest/appveyor.yml
testing/web-platform/tests/tools/third_party/pytest/bench/bench.py
testing/web-platform/tests/tools/third_party/pytest/bench/bench_argcomplete.py
testing/web-platform/tests/tools/third_party/pytest/bench/empty.py
testing/web-platform/tests/tools/third_party/pytest/bench/manyparam.py
testing/web-platform/tests/tools/third_party/pytest/bench/skip.py
testing/web-platform/tests/tools/third_party/pytest/changelog/2920.bugfix
testing/web-platform/tests/tools/third_party/pytest/changelog/2949.trivial
testing/web-platform/tests/tools/third_party/pytest/changelog/2956.bugfix
testing/web-platform/tests/tools/third_party/pytest/changelog/2957.bugfix
testing/web-platform/tests/tools/third_party/pytest/changelog/2963.doc
testing/web-platform/tests/tools/third_party/pytest/changelog/2971.bugfix
testing/web-platform/tests/tools/third_party/pytest/changelog/2984.bugfix
testing/web-platform/tests/tools/third_party/pytest/changelog/README.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/_templates/globaltoc.html
testing/web-platform/tests/tools/third_party/pytest/doc/en/_templates/links.html
testing/web-platform/tests/tools/third_party/pytest/doc/en/_themes/flask/theme.conf
testing/web-platform/tests/tools/third_party/pytest/doc/en/_themes/flask_theme_support.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/index.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.0.3.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.1.1.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.1.2.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.1.3.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.2.1.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.2.2.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.2.4.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.0.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.1.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.2.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.3.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.4.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.5.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.4.0.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.4.1.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.4.2.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.5.0.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.5.1.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.5.2.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.6.1.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.6.2.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.6.3.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.7.0.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.7.2.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.8.3.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.8.7.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.9.0.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.9.1.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.0.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.1.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.2.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.3.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.4.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.5.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.6.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.7.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.1.1.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.1.2.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.1.3.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.1.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.2.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.3.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.4.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.5.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.3.1.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.3.2.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.4.0.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.4.1.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.4.2.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.5.0.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.5.1.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.6.0.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.6.1.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.6.2.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/assert.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/backwards-compatibility.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/bash-completion.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/builtin.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/cache.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/capture.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/check_sphinx.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/conf.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/contact.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/contents.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/customize.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/development_guide.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/doctest.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/failure_demo.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/global_testmodule_config/conftest.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/global_testmodule_config/test_hello.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/global_testmodule_config/test_hello_world.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/test_failures.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/test_setup_flow_example.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/attic.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/conftest.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub1/__init__.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub1/test_quick.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub2/__init__.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub2/test_two.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub_a/__init__.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub_a/test_quick.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub_b/__init__.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub_b/test_two.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/markers.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/multipython.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/nonpython.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/nonpython/conftest.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/parametrize.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/py2py3/conftest.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/py2py3/test_py2.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/py2py3/test_py3.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/pythoncollection.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/pythoncollection.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/reportingdemo.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/simple.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/special.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/example/xfail_demo.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/faq.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/fixture.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/funcarg_compare.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/funcargs.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/genapi.py
testing/web-platform/tests/tools/third_party/pytest/doc/en/getting-started.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/goodpractices.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/index.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/links.inc
testing/web-platform/tests/tools/third_party/pytest/doc/en/logging.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/mark.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/monkeypatch.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/nose.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/parametrize.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/plugins.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/projects.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/proposals/parametrize_with_fixtures.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/reference.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/requirements.txt
testing/web-platform/tests/tools/third_party/pytest/doc/en/skipping.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/talks.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/attic.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/config.html
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/dist.html
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/extend.html
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/index.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/mission.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/cov.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/coverage.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/django.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/figleaf.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/helpconfig.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/index.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/links.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/nose.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/oejskit.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/terminal.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/xdist.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/test/test.html
testing/web-platform/tests/tools/third_party/pytest/doc/en/tmpdir.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/unittest.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/usage.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/warnings.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/writing_plugins.rst
testing/web-platform/tests/tools/third_party/pytest/doc/en/xunit_setup.rst
testing/web-platform/tests/tools/third_party/pytest/extra/get_issues.py
testing/web-platform/tests/tools/third_party/pytest/pyproject.toml
testing/web-platform/tests/tools/third_party/pytest/pytest.py
testing/web-platform/tests/tools/third_party/pytest/scripts/check-rst.py
testing/web-platform/tests/tools/third_party/pytest/setup.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/__init__.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/_argcomplete.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/_code/__init__.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/_code/_py2traceback.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/_code/code.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/_code/source.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/assertion/__init__.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/assertion/rewrite.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/assertion/truncate.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/assertion/util.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/cacheprovider.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/capture.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/compat.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/config/__init__.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/config/argparsing.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/config/exceptions.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/config/findpaths.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/debugging.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/deprecated.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/doctest.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/fixtures.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/freeze_support.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/helpconfig.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/hookspec.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/junitxml.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/logging.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/main.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/mark/__init__.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/mark/evaluate.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/mark/legacy.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/mark/structures.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/monkeypatch.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/nodes.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/nose.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/outcomes.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/pastebin.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/pytester.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/python.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/python_api.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/recwarn.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/resultlog.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/runner.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/setuponly.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/setupplan.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/skipping.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/terminal.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/tmpdir.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/unittest.py
testing/web-platform/tests/tools/third_party/pytest/src/_pytest/warnings.py
testing/web-platform/tests/tools/third_party/pytest/src/pytest.py
testing/web-platform/tests/tools/third_party/pytest/tasks/__init__.py
testing/web-platform/tests/tools/third_party/pytest/tasks/generate.py
testing/web-platform/tests/tools/third_party/pytest/tasks/release.minor.rst
testing/web-platform/tests/tools/third_party/pytest/tasks/release.patch.rst
testing/web-platform/tests/tools/third_party/pytest/tasks/requirements.txt
testing/web-platform/tests/tools/third_party/pytest/testing/acceptance_test.py
testing/web-platform/tests/tools/third_party/pytest/testing/code/test_code.py
testing/web-platform/tests/tools/third_party/pytest/testing/code/test_excinfo.py
testing/web-platform/tests/tools/third_party/pytest/testing/code/test_source.py
testing/web-platform/tests/tools/third_party/pytest/testing/code/test_source_multiline_block.py
testing/web-platform/tests/tools/third_party/pytest/testing/deprecated_test.py
testing/web-platform/tests/tools/third_party/pytest/testing/freeze/.gitignore
testing/web-platform/tests/tools/third_party/pytest/testing/freeze/create_executable.py
testing/web-platform/tests/tools/third_party/pytest/testing/freeze/runtests_script.py
testing/web-platform/tests/tools/third_party/pytest/testing/freeze/tests/test_trivial.py
testing/web-platform/tests/tools/third_party/pytest/testing/freeze/tox_run.py
testing/web-platform/tests/tools/third_party/pytest/testing/logging/test_fixture.py
testing/web-platform/tests/tools/third_party/pytest/testing/logging/test_formatter.py
testing/web-platform/tests/tools/third_party/pytest/testing/logging/test_reporting.py
testing/web-platform/tests/tools/third_party/pytest/testing/python/approx.py
testing/web-platform/tests/tools/third_party/pytest/testing/python/collect.py
testing/web-platform/tests/tools/third_party/pytest/testing/python/fixture.py
testing/web-platform/tests/tools/third_party/pytest/testing/python/integration.py
testing/web-platform/tests/tools/third_party/pytest/testing/python/metafunc.py
testing/web-platform/tests/tools/third_party/pytest/testing/python/raises.py
testing/web-platform/tests/tools/third_party/pytest/testing/python/setup_only.py
testing/web-platform/tests/tools/third_party/pytest/testing/python/setup_plan.py
testing/web-platform/tests/tools/third_party/pytest/testing/python/show_fixtures_per_test.py
testing/web-platform/tests/tools/third_party/pytest/testing/python/test_deprecations.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_argcomplete.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_assertion.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_assertrewrite.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_cache.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_cacheprovider.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_capture.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_collection.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_compat.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_config.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_conftest.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_doctest.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_entry_points.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_helpconfig.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_junitxml.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_mark.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_modimport.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_monkeypatch.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_nodes.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_nose.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_parseopt.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_pastebin.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_pdb.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_pluginmanager.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_pytester.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_recwarn.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_resultlog.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_runner.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_runner_xunit.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_session.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_skipping.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_terminal.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_tmpdir.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_unittest.py
testing/web-platform/tests/tools/third_party/pytest/testing/test_warnings.py
testing/web-platform/tests/tools/third_party/pytest/tox.ini
--- a/testing/web-platform/tests/tools/localpaths.py
+++ b/testing/web-platform/tests/tools/localpaths.py
@@ -10,11 +10,11 @@ sys.path.insert(0, os.path.join(here, "h
 sys.path.insert(0, os.path.join(here, "wptserve"))
 sys.path.insert(0, os.path.join(here, "pywebsocket"))
 sys.path.insert(0, os.path.join(here, "third_party", "atomicwrites"))
 sys.path.insert(0, os.path.join(here, "third_party", "attrs", "src"))
 sys.path.insert(0, os.path.join(here, "third_party", "funcsigs"))
 sys.path.insert(0, os.path.join(here, "third_party", "more-itertools"))
 sys.path.insert(0, os.path.join(here, "third_party", "pluggy"))
 sys.path.insert(0, os.path.join(here, "third_party", "py"))
-sys.path.insert(0, os.path.join(here, "third_party", "pytest"))
+sys.path.insert(0, os.path.join(here, "third_party", "pytest", "src"))
 sys.path.insert(0, os.path.join(here, "webdriver"))
 sys.path.insert(0, os.path.join(here, "wptrunner"))
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/.coveragerc
@@ -0,0 +1,4 @@
+[run]
+omit =
+    # standlonetemplate is read dynamically and tested by test_genscript
+    *standalonetemplate.py
--- a/testing/web-platform/tests/tools/third_party/pytest/.github/PULL_REQUEST_TEMPLATE.md
+++ b/testing/web-platform/tests/tools/third_party/pytest/.github/PULL_REQUEST_TEMPLATE.md
@@ -1,15 +1,14 @@
 Thanks for submitting a PR, your contribution is really appreciated!
 
-Here's a quick checklist that should be present in PRs:
+Here's a quick checklist that should be present in PRs (you can delete this text from the final description, this is
+just a guideline):
 
-- [ ] Add a new news fragment into the changelog folder
-  * name it `$issue_id.$type` for example (588.bug)
-  * if you don't have an issue_id change it to the pr id after creating the pr
-  * ensure type is one of `removal`, `feature`, `bugfix`, `vendor`, `doc` or `trivial`
-  * Make sure to use full sentences with correct case and punctuation, for example: "Fix issue with non-ascii contents in doctest text files."
-- [ ] Target: for `bugfix`, `vendor`, `doc` or `trivial` fixes, target `master`; for removals or features target `features`;
-- [ ] Make sure to include reasonable tests for your change if necessary
+- [ ] Create a new changelog file in the `changelog` folder, with a name like `<ISSUE NUMBER>.<TYPE>.rst`. See [changelog/README.rst](/changelog/README.rst) for details.
+- [ ] Target the `master` branch for bug fixes, documentation updates and trivial changes.
+- [ ] Target the `features` branch for new features and removals/deprecations.
+- [ ] Include documentation when adding new features.
+- [ ] Include new tests or update existing tests when applicable.
 
-Unless your change is a trivial or a documentation fix (e.g.,  a typo or reword of a small section) please:
+Unless your change is trivial or a small documentation fix (e.g.,  a typo or reword of a small section) please:
 
-- [ ] Add yourself to `AUTHORS`, in alphabetical order;
+- [ ] Add yourself to `AUTHORS` in alphabetical order;
--- a/testing/web-platform/tests/tools/third_party/pytest/.gitignore
+++ b/testing/web-platform/tests/tools/third_party/pytest/.gitignore
@@ -14,26 +14,27 @@ include/
 *.pyo
 *.swp
 *.class
 *.orig
 *~
 .hypothesis/
 
 # autogenerated
-_pytest/_version.py
+src/_pytest/_version.py
 # setuptools
 .eggs/
 
 doc/*/_build
 build/
 dist/
 *.egg-info
 issue/
 env/
 .env/
 3rdparty/
 .tox
 .cache
+.pytest_cache
 .coverage
 .ropeproject
 .idea
 .hypothesis
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/.pre-commit-config.yaml
@@ -0,0 +1,36 @@
+exclude: doc/en/example/py2py3/test_py2.py
+repos:
+-   repo: https://github.com/ambv/black
+    rev: 18.4a4
+    hooks:
+    -   id: black
+        args: [--safe, --quiet]
+        language_version: python3.6
+-   repo: https://github.com/asottile/blacken-docs
+    rev: v0.1.1
+    hooks:
+    -   id: blacken-docs
+        additional_dependencies: [black==18.5b1]
+        language_version: python3.6
+-   repo: https://github.com/pre-commit/pre-commit-hooks
+    rev: v1.2.3
+    hooks:
+    -   id: trailing-whitespace
+    -   id: end-of-file-fixer
+    -   id: check-yaml
+    -   id: debug-statements
+        exclude: _pytest/debugging.py
+    -   id: flake8
+-   repo: https://github.com/asottile/pyupgrade
+    rev: v1.2.0
+    hooks:
+    - id: pyupgrade
+-   repo: local
+    hooks:
+    -   id: rst
+        name: rst
+        entry: rst-lint --encoding utf-8
+        files: ^(CHANGELOG.rst|HOWTORELEASE.rst|README.rst|changelog/.*)$
+        language: python
+        additional_dependencies: [pygments, restructuredtext_lint]
+        python_version: python3.6
--- a/testing/web-platform/tests/tools/third_party/pytest/.travis.yml
+++ b/testing/web-platform/tests/tools/third_party/pytest/.travis.yml
@@ -1,22 +1,24 @@
 sudo: false
 language: python
+stages:
+- linting
+- test
+- deploy
 python:
   - '3.6'
-# command to install dependencies
 install:
   - pip install --upgrade --pre tox
-# # command to run tests
 env:
   matrix:
     # coveralls is not listed in tox's envlist, but should run in travis
     - TOXENV=coveralls
     # note: please use "tox --listenvs" to populate the build matrix below
-    - TOXENV=linting
+    # please remove the linting env in all cases
     - TOXENV=py27
     - TOXENV=py34
     - TOXENV=py36
     - TOXENV=py27-pexpect
     - TOXENV=py27-xdist
     - TOXENV=py27-trial
     - TOXENV=py27-numpy
     - TOXENV=py27-pluggymaster
@@ -24,33 +26,58 @@ env:
     - TOXENV=py36-xdist
     - TOXENV=py36-trial
     - TOXENV=py36-numpy
     - TOXENV=py36-pluggymaster
     - TOXENV=py27-nobyte
     - TOXENV=doctesting
     - TOXENV=docs
 
-matrix:
+jobs:
   include:
     - env: TOXENV=pypy
       python: 'pypy-5.4'
     - env: TOXENV=py35
       python: '3.5'
     - env: TOXENV=py35-freeze
       python: '3.5'
     - env: TOXENV=py37
       python: 'nightly'
-  allow_failures:
-    - env: TOXENV=py37
-      python: 'nightly'
+
+    - stage: deploy
+      python: '3.6'
+      env:
+      install: pip install -U setuptools setuptools_scm
+      script: skip
+      deploy:
+        provider: pypi
+        user: nicoddemus
+        distributions: sdist bdist_wheel
+        skip_upload_docs: true
+        password:
+          secure: xanTgTUu6XDQVqB/0bwJQXoDMnU5tkwZc5koz6mBkkqZhKdNOi2CLoC1XhiSZ+ah24l4V1E0GAqY5kBBcy9d7NVe4WNg4tD095LsHw+CRU6/HCVIFfyk2IZ+FPAlguesCcUiJSXOrlBF+Wj68wEvLoK7EoRFbJeiZ/f91Ww1sbtDlqXABWGHrmhPJL5Wva7o7+wG7JwJowqdZg1pbQExsCc7b53w4v2RBu3D6TJaTAzHiVsW+nUSI67vKI/uf+cR/OixsTfy37wlHgSwihYmrYLFls3V0bSpahCim3bCgMaFZx8S8xrdgJ++PzBCof2HeflFKvW+VCkoYzGEG4NrTWJoNz6ni4red9GdvfjGH3YCjAKS56h9x58zp2E5rpsb/kVq5/45xzV+dq6JRuhQ1nJWjBC6fSKAc/bfwnuFK3EBxNLkvBssLHvsNjj5XG++cB8DdS9wVGUqjpoK4puaXUWFqy4q3S9F86HEsKNgExtieA9qNx+pCIZVs6JCXZNjr0I5eVNzqJIyggNgJG6RyravsU35t9Zd9doL5g4Y7UKmAGTn1Sz24HQ4sMQgXdm2SyD8gEK5je4tlhUvfGtDvMSlstq71kIn9nRpFnqB6MFlbYSEAZmo8dGbCquoUc++6Rum208wcVbrzzVtGlXB/Ow9AbFMYeAGA0+N/K1e59c=
+        on:
+          tags: true
+          repo: pytest-dev/pytest
+    - stage: linting
+      python: '3.6'
+      env:
+      install:
+      - pip install pre-commit
+      - pre-commit install-hooks
+      script:
+      - pre-commit run --all-files
 
 script: tox --recreate
 
 notifications:
   irc:
     channels:
       - "chat.freenode.net#pytest"
     on_success: change
     on_failure: change
     skip_join: true
   email:
     - pytest-commit@python.org
+cache:
+    directories:
+        - $HOME/.cache/pip
+        - $HOME/.cache/pre-commit
--- a/testing/web-platform/tests/tools/third_party/pytest/AUTHORS
+++ b/testing/web-platform/tests/tools/third_party/pytest/AUTHORS
@@ -1,48 +1,57 @@
 Holger Krekel, holger at merlinux eu
 merlinux GmbH, Germany, office at merlinux eu
 
 Contributors include::
 
+Aaron Coleman
 Abdeali JK
 Abhijeet Kasurde
 Ahn Ki-Wook
+Alan Velasco
 Alexander Johnson
 Alexei Kozlenok
 Anatoly Bubenkoff
+Anders Hovmöller
 Andras Tim
 Andreas Zeidler
 Andrzej Ostrowski
 Andy Freeland
 Anthon van der Neut
+Anthony Shaw
 Anthony Sottile
 Antony Lee
 Armin Rigo
+Aron Coyle
 Aron Curzon
+Aviral Verma
 Aviv Palivoda
 Barney Gale
 Ben Webb
 Benjamin Peterson
 Bernard Pratz
 Bob Ippolito
 Brian Dorsey
+Brian Maissy
 Brian Okken
 Brianna Laugher
 Bruno Oliveira
 Cal Leeming
 Carl Friedrich Bolz
+Carlos Jenkins
 Ceridwen
 Charles Cloud
 Charnjit SiNGH (CCSJ)
 Chris Lamb
 Christian Boelsen
 Christian Theunert
 Christian Tismer
 Christopher Gilling
+Cyrus Maden
 Daniel Grana
 Daniel Hahler
 Daniel Nuri
 Daniel Wandschneider
 Danielle Jenkins
 Dave Hunt
 David Díaz-Barquero
 David Mohr
@@ -68,40 +77,47 @@ Floris Bruynooghe
 Gabriel Reis
 George Kussumoto
 Georgy Dyuldin
 Graham Horler
 Greg Price
 Grig Gheorghiu
 Grigorii Eremeev (budulianin)
 Guido Wesdorp
+Guoqiang Zhang
 Harald Armin Massa
+Henk-Jaap Wagenaar
 Hugo van Kemenade
 Hui Wang (coldnight)
 Ian Bicking
+Ian Lesperance
 Jaap Broekhuizen
 Jan Balster
 Janne Vanhala
 Jason R. Coombs
 Javier Domingo Cansino
 Javier Romero
+Jeff Rackauckas
 Jeff Widman
 John Eddie Ayson
 John Towler
 Jon Sonesen
 Jonas Obrist
 Jordan Guymon
 Jordan Moldow
+Jordan Speicher
 Joshua Bronson
 Jurko Gospodnetić
 Justyna Janczyszyn
 Kale Kundert
 Katarzyna Jachim
+Katerina Koukiou
 Kevin Cox
 Kodi B. Arfer
+Kostis Anagnostopoulos
 Lawrence Mitchell
 Lee Kamentsky
 Lev Maximov
 Llandy Riveron Del Risco
 Loic Esteve
 Lukas Bednar
 Luke Murphy
 Maciek Fijalkowski
@@ -126,32 +142,36 @@ Maxim Filipenko
 mbyt
 Michael Aquilina
 Michael Birtwell
 Michael Droettboom
 Michael Seifert
 Michal Wajszczuk
 Mihai Capotă
 Mike Lundy
+Miro Hrončok
 Nathaniel Waisbrot
 Ned Batchelder
 Neven Mundar
 Nicolas Delaby
 Oleg Pidsadnyi
+Oleg Sushchenko
 Oliver Bestwalter
 Omar Kohl
 Omer Hadari
 Patrick Hayes
 Paweł Adamczak
+Pedro Algarvio
 Pieter Mulder
 Piotr Banaszkiewicz
 Punyashloka Biswal
 Quentin Pradet
 Ralf Schmitt
 Ran Benita
+Raphael Castaneda
 Raphael Pierzina
 Raquel Alegre
 Ravi Chandra
 Roberto Polli
 Romain Dorgueil
 Roman Bolshakov
 Ronny Pfannschmidt
 Ross Lawley
@@ -168,22 +188,26 @@ Stefan Zimmermann
 Stefano Taschini
 Steffen Allner
 Stephan Obermann
 Tarcisio Fischer
 Tareq Alayan
 Ted Xiao
 Thomas Grainger
 Thomas Hisch
+Tim Strazny
 Tom Dalton
 Tom Viner
 Trevor Bekolay
 Tyler Goodlet
+Tzu-ping Chung
 Vasily Kuznetsov
 Victor Uriarte
 Vidar T. Fauske
 Vitaly Lashmanov
 Vlad Dragos
+William Lee
 Wouter van Ackooy
 Xuan Luong
 Xuecong Liao
 Zoltán Máté
 Roland Puntaier
+Allan Feldman
--- a/testing/web-platform/tests/tools/third_party/pytest/CHANGELOG.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/CHANGELOG.rst
@@ -1,18 +1,707 @@
-.. 
+..
     You should *NOT* be adding new change log entries to this file, this
     file is managed by towncrier. You *may* edit previous change logs to
     fix problems like typo corrections or such.
     To add a new change log entry, please see
     https://pip.pypa.io/en/latest/development/#adding-a-news-entry
     we named the news folder changelog
 
 .. towncrier release notes start
 
+Pytest 3.6.2 (2018-06-20)
+=========================
+
+Bug Fixes
+---------
+
+- Fix regression in ``Node.add_marker`` by extracting the mark object of a
+  ``MarkDecorator``. (`#3555
+  <https://github.com/pytest-dev/pytest/issues/3555>`_)
+
+- Warnings without ``location`` were reported as ``None``. This is corrected to
+  now report ``<undetermined location>``. (`#3563
+  <https://github.com/pytest-dev/pytest/issues/3563>`_)
+
+- Continue to call finalizers in the stack when a finalizer in a former scope
+  raises an exception. (`#3569
+  <https://github.com/pytest-dev/pytest/issues/3569>`_)
+
+- Fix encoding error with `print` statements in doctests (`#3583
+  <https://github.com/pytest-dev/pytest/issues/3583>`_)
+
+
+Improved Documentation
+----------------------
+
+- Add documentation for the ``--strict`` flag. (`#3549
+  <https://github.com/pytest-dev/pytest/issues/3549>`_)
+
+
+Trivial/Internal Changes
+------------------------
+
+- Update old quotation style to parens in fixture.rst documentation. (`#3525
+  <https://github.com/pytest-dev/pytest/issues/3525>`_)
+
+- Improve display of hint about ``--fulltrace`` with ``KeyboardInterrupt``.
+  (`#3545 <https://github.com/pytest-dev/pytest/issues/3545>`_)
+
+- pytest's testsuite is no longer runnable through ``python setup.py test`` --
+  instead invoke ``pytest`` or ``tox`` directly. (`#3552
+  <https://github.com/pytest-dev/pytest/issues/3552>`_)
+
+- Fix typo in documentation (`#3567
+  <https://github.com/pytest-dev/pytest/issues/3567>`_)
+
+
+Pytest 3.6.1 (2018-06-05)
+=========================
+
+Bug Fixes
+---------
+
+- Fixed a bug where stdout and stderr were logged twice by junitxml when a test
+  was marked xfail. (`#3491
+  <https://github.com/pytest-dev/pytest/issues/3491>`_)
+
+- Fix ``usefixtures`` mark applyed to unittest tests by correctly instantiating
+  ``FixtureInfo``. (`#3498
+  <https://github.com/pytest-dev/pytest/issues/3498>`_)
+
+- Fix assertion rewriter compatibility with libraries that monkey patch
+  ``file`` objects. (`#3503
+  <https://github.com/pytest-dev/pytest/issues/3503>`_)
+
+
+Improved Documentation
+----------------------
+
+- Added a section on how to use fixtures as factories to the fixture
+  documentation. (`#3461 <https://github.com/pytest-dev/pytest/issues/3461>`_)
+
+
+Trivial/Internal Changes
+------------------------
+
+- Enable caching for pip/pre-commit in order to reduce build time on
+  travis/appveyor. (`#3502
+  <https://github.com/pytest-dev/pytest/issues/3502>`_)
+
+- Switch pytest to the src/ layout as we already suggested it for good practice
+  - now we implement it as well. (`#3513
+  <https://github.com/pytest-dev/pytest/issues/3513>`_)
+
+- Fix if in tests to support 3.7.0b5, where a docstring handling in AST got
+  reverted. (`#3530 <https://github.com/pytest-dev/pytest/issues/3530>`_)
+
+- Remove some python2.5 compatibility code. (`#3529
+  <https://github.com/pytest-dev/pytest/issues/3529>`_)
+
+
+Pytest 3.6.0 (2018-05-23)
+=========================
+
+Features
+--------
+
+- Revamp the internals of the ``pytest.mark`` implementation with correct per
+  node handling which fixes a number of long standing bugs caused by the old
+  design. This introduces new ``Node.iter_markers(name)`` and
+  ``Node.get_closest_mark(name)`` APIs. Users are **strongly encouraged** to
+  read the `reasons for the revamp in the docs
+  <https://docs.pytest.org/en/latest/mark.html#marker-revamp-and-iteration>`_,
+  or jump over to details about `updating existing code to use the new APIs
+  <https://docs.pytest.org/en/latest/mark.html#updating-code>`_. (`#3317
+  <https://github.com/pytest-dev/pytest/issues/3317>`_)
+
+- Now when ``@pytest.fixture`` is applied more than once to the same function a
+  ``ValueError`` is raised. This buggy behavior would cause surprising problems
+  and if was working for a test suite it was mostly by accident. (`#2334
+  <https://github.com/pytest-dev/pytest/issues/2334>`_)
+
+- Support for Python 3.7's builtin ``breakpoint()`` method, see `Using the
+  builtin breakpoint function
+  <https://docs.pytest.org/en/latest/usage.html#breakpoint-builtin>`_ for
+  details. (`#3180 <https://github.com/pytest-dev/pytest/issues/3180>`_)
+
+- ``monkeypatch`` now supports a ``context()`` function which acts as a context
+  manager which undoes all patching done within the ``with`` block. (`#3290
+  <https://github.com/pytest-dev/pytest/issues/3290>`_)
+
+- The ``--pdb`` option now causes KeyboardInterrupt to enter the debugger,
+  instead of stopping the test session. On python 2.7, hitting CTRL+C again
+  exits the debugger. On python 3.2 and higher, use CTRL+D. (`#3299
+  <https://github.com/pytest-dev/pytest/issues/3299>`_)
+
+- pytest not longer changes the log level of the root logger when the
+  ``log-level`` parameter has greater numeric value than that of the level of
+  the root logger, which makes it play better with custom logging configuration
+  in user code. (`#3307 <https://github.com/pytest-dev/pytest/issues/3307>`_)
+
+
+Bug Fixes
+---------
+
+- A rare race-condition which might result in corrupted ``.pyc`` files on
+  Windows has been hopefully solved. (`#3008
+  <https://github.com/pytest-dev/pytest/issues/3008>`_)
+
+- Also use iter_marker for discovering the marks applying for marker
+  expressions from the cli to avoid the bad data from the legacy mark storage.
+  (`#3441 <https://github.com/pytest-dev/pytest/issues/3441>`_)
+
+- When showing diffs of failed assertions where the contents contain only
+  whitespace, escape them using ``repr()`` first to make it easy to spot the
+  differences. (`#3443 <https://github.com/pytest-dev/pytest/issues/3443>`_)
+
+
+Improved Documentation
+----------------------
+
+- Change documentation copyright year to a range which auto-updates itself each
+  time it is published. (`#3303
+  <https://github.com/pytest-dev/pytest/issues/3303>`_)
+
+
+Trivial/Internal Changes
+------------------------
+
+- ``pytest`` now depends on the `python-atomicwrites
+  <https://github.com/untitaker/python-atomicwrites>`_ library. (`#3008
+  <https://github.com/pytest-dev/pytest/issues/3008>`_)
+
+- Update all pypi.python.org URLs to pypi.org. (`#3431
+  <https://github.com/pytest-dev/pytest/issues/3431>`_)
+
+- Detect `pytest_` prefixed hooks using the internal plugin manager since
+  ``pluggy`` is deprecating the ``implprefix`` argument to ``PluginManager``.
+  (`#3487 <https://github.com/pytest-dev/pytest/issues/3487>`_)
+
+- Import ``Mapping`` and ``Sequence`` from ``_pytest.compat`` instead of
+  directly from ``collections`` in ``python_api.py::approx``. Add ``Mapping``
+  to ``_pytest.compat``, import it from ``collections`` on python 2, but from
+  ``collections.abc`` on Python 3 to avoid a ``DeprecationWarning`` on Python
+  3.7 or newer. (`#3497 <https://github.com/pytest-dev/pytest/issues/3497>`_)
+
+
+Pytest 3.5.1 (2018-04-23)
+=========================
+
+
+Bug Fixes
+---------
+
+- Reset ``sys.last_type``, ``sys.last_value`` and ``sys.last_traceback`` before
+  each test executes. Those attributes are added by pytest during the test run
+  to aid debugging, but were never reset so they would create a leaking
+  reference to the last failing test's frame which in turn could never be
+  reclaimed by the garbage collector. (`#2798
+  <https://github.com/pytest-dev/pytest/issues/2798>`_)
+
+- ``pytest.raises`` now raises ``TypeError`` when receiving an unknown keyword
+  argument. (`#3348 <https://github.com/pytest-dev/pytest/issues/3348>`_)
+
+- ``pytest.raises`` now works with exception classes that look like iterables.
+  (`#3372 <https://github.com/pytest-dev/pytest/issues/3372>`_)
+
+
+Improved Documentation
+----------------------
+
+- Fix typo in ``caplog`` fixture documentation, which incorrectly identified
+  certain attributes as methods. (`#3406
+  <https://github.com/pytest-dev/pytest/issues/3406>`_)
+
+
+Trivial/Internal Changes
+------------------------
+
+- Added a more indicative error message when parametrizing a function whose
+  argument takes a default value. (`#3221
+  <https://github.com/pytest-dev/pytest/issues/3221>`_)
+
+- Remove internal ``_pytest.terminal.flatten`` function in favor of
+  ``more_itertools.collapse``. (`#3330
+  <https://github.com/pytest-dev/pytest/issues/3330>`_)
+
+- Import some modules from ``collections.abc`` instead of ``collections`` as
+  the former modules trigger ``DeprecationWarning`` in Python 3.7. (`#3339
+  <https://github.com/pytest-dev/pytest/issues/3339>`_)
+
+- record_property is no longer experimental, removing the warnings was
+  forgotten. (`#3360 <https://github.com/pytest-dev/pytest/issues/3360>`_)
+
+- Mention in documentation and CLI help that fixtures with leading ``_`` are
+  printed by ``pytest --fixtures`` only if the ``-v`` option is added. (`#3398
+  <https://github.com/pytest-dev/pytest/issues/3398>`_)
+
+
+Pytest 3.5.0 (2018-03-21)
+=========================
+
+Deprecations and Removals
+-------------------------
+
+- ``record_xml_property`` fixture is now deprecated in favor of the more
+  generic ``record_property``. (`#2770
+  <https://github.com/pytest-dev/pytest/issues/2770>`_)
+
+- Defining ``pytest_plugins`` is now deprecated in non-top-level conftest.py
+  files, because they "leak" to the entire directory tree. (`#3084
+  <https://github.com/pytest-dev/pytest/issues/3084>`_)
+
+
+Features
+--------
+
+- New ``--show-capture`` command-line option that allows to specify how to
+  display captured output when tests fail: ``no``, ``stdout``, ``stderr``,
+  ``log`` or ``all`` (the default). (`#1478
+  <https://github.com/pytest-dev/pytest/issues/1478>`_)
+
+- New ``--rootdir`` command-line option to override the rules for discovering
+  the root directory. See `customize
+  <https://docs.pytest.org/en/latest/customize.html>`_ in the documentation for
+  details. (`#1642 <https://github.com/pytest-dev/pytest/issues/1642>`_)
+
+- Fixtures are now instantiated based on their scopes, with higher-scoped
+  fixtures (such as ``session``) being instantiated first than lower-scoped
+  fixtures (such as ``function``). The relative order of fixtures of the same
+  scope is kept unchanged, based in their declaration order and their
+  dependencies. (`#2405 <https://github.com/pytest-dev/pytest/issues/2405>`_)
+
+- ``record_xml_property`` renamed to ``record_property`` and is now compatible
+  with xdist, markers and any reporter. ``record_xml_property`` name is now
+  deprecated. (`#2770 <https://github.com/pytest-dev/pytest/issues/2770>`_)
+
+- New ``--nf``, ``--new-first`` options: run new tests first followed by the
+  rest of the tests, in both cases tests are also sorted by the file modified
+  time, with more recent files coming first. (`#3034
+  <https://github.com/pytest-dev/pytest/issues/3034>`_)
+
+- New ``--last-failed-no-failures`` command-line option that allows to specify
+  the behavior of the cache plugin's ```--last-failed`` feature when no tests
+  failed in the last run (or no cache was found): ``none`` or ``all`` (the
+  default). (`#3139 <https://github.com/pytest-dev/pytest/issues/3139>`_)
+
+- New ``--doctest-continue-on-failure`` command-line option to enable doctests
+  to show multiple failures for each snippet, instead of stopping at the first
+  failure. (`#3149 <https://github.com/pytest-dev/pytest/issues/3149>`_)
+
+- Captured log messages are added to the ``<system-out>`` tag in the generated
+  junit xml file if the ``junit_logging`` ini option is set to ``system-out``.
+  If the value of this ini option is ``system-err``, the logs are written to
+  ``<system-err>``. The default value for ``junit_logging`` is ``no``, meaning
+  captured logs are not written to the output file. (`#3156
+  <https://github.com/pytest-dev/pytest/issues/3156>`_)
+
+- Allow the logging plugin to handle ``pytest_runtest_logstart`` and
+  ``pytest_runtest_logfinish`` hooks when live logs are enabled. (`#3189
+  <https://github.com/pytest-dev/pytest/issues/3189>`_)
+
+- Passing `--log-cli-level` in the command-line now automatically activates
+  live logging. (`#3190 <https://github.com/pytest-dev/pytest/issues/3190>`_)
+
+- Add command line option ``--deselect`` to allow deselection of individual
+  tests at collection time. (`#3198
+  <https://github.com/pytest-dev/pytest/issues/3198>`_)
+
+- Captured logs are printed before entering pdb. (`#3204
+  <https://github.com/pytest-dev/pytest/issues/3204>`_)
+
+- Deselected item count is now shown before tests are run, e.g. ``collected X
+  items / Y deselected``. (`#3213
+  <https://github.com/pytest-dev/pytest/issues/3213>`_)
+
+- The builtin module ``platform`` is now available for use in expressions in
+  ``pytest.mark``. (`#3236
+  <https://github.com/pytest-dev/pytest/issues/3236>`_)
+
+- The *short test summary info* section now is displayed after tracebacks and
+  warnings in the terminal. (`#3255
+  <https://github.com/pytest-dev/pytest/issues/3255>`_)
+
+- New ``--verbosity`` flag to set verbosity level explicitly. (`#3296
+  <https://github.com/pytest-dev/pytest/issues/3296>`_)
+
+- ``pytest.approx`` now accepts comparing a numpy array with a scalar. (`#3312
+  <https://github.com/pytest-dev/pytest/issues/3312>`_)
+
+
+Bug Fixes
+---------
+
+- Suppress ``IOError`` when closing the temporary file used for capturing
+  streams in Python 2.7. (`#2370
+  <https://github.com/pytest-dev/pytest/issues/2370>`_)
+
+- Fixed ``clear()`` method on ``caplog`` fixture which cleared ``records``, but
+  not the ``text`` property. (`#3297
+  <https://github.com/pytest-dev/pytest/issues/3297>`_)
+
+- During test collection, when stdin is not allowed to be read, the
+  ``DontReadFromStdin`` object still allow itself to be iterable and resolved
+  to an iterator without crashing. (`#3314
+  <https://github.com/pytest-dev/pytest/issues/3314>`_)
+
+
+Improved Documentation
+----------------------
+
+- Added a `reference <https://docs.pytest.org/en/latest/reference.html>`_ page
+  to the docs. (`#1713 <https://github.com/pytest-dev/pytest/issues/1713>`_)
+
+
+Trivial/Internal Changes
+------------------------
+
+- Change minimum requirement of ``attrs`` to ``17.4.0``. (`#3228
+  <https://github.com/pytest-dev/pytest/issues/3228>`_)
+
+- Renamed example directories so all tests pass when ran from the base
+  directory. (`#3245 <https://github.com/pytest-dev/pytest/issues/3245>`_)
+
+- Internal ``mark.py`` module has been turned into a package. (`#3250
+  <https://github.com/pytest-dev/pytest/issues/3250>`_)
+
+- ``pytest`` now depends on the `more-itertools
+  <https://github.com/erikrose/more-itertools>`_ package. (`#3265
+  <https://github.com/pytest-dev/pytest/issues/3265>`_)
+
+- Added warning when ``[pytest]`` section is used in a ``.cfg`` file passed
+  with ``-c`` (`#3268 <https://github.com/pytest-dev/pytest/issues/3268>`_)
+
+- ``nodeids`` can now be passed explicitly to ``FSCollector`` and ``Node``
+  constructors. (`#3291 <https://github.com/pytest-dev/pytest/issues/3291>`_)
+
+- Internal refactoring of ``FormattedExcinfo`` to use ``attrs`` facilities and
+  remove old support code for legacy Python versions. (`#3292
+  <https://github.com/pytest-dev/pytest/issues/3292>`_)
+
+- Refactoring to unify how verbosity is handled internally. (`#3296
+  <https://github.com/pytest-dev/pytest/issues/3296>`_)
+
+- Internal refactoring to better integrate with argparse. (`#3304
+  <https://github.com/pytest-dev/pytest/issues/3304>`_)
+
+- Fix a python example when calling a fixture in doc/en/usage.rst (`#3308
+  <https://github.com/pytest-dev/pytest/issues/3308>`_)
+
+
+Pytest 3.4.2 (2018-03-04)
+=========================
+
+Bug Fixes
+---------
+
+- Removed progress information when capture option is ``no``. (`#3203
+  <https://github.com/pytest-dev/pytest/issues/3203>`_)
+
+- Refactor check of bindir from ``exists`` to ``isdir``. (`#3241
+  <https://github.com/pytest-dev/pytest/issues/3241>`_)
+
+- Fix ``TypeError`` issue when using ``approx`` with a ``Decimal`` value.
+  (`#3247 <https://github.com/pytest-dev/pytest/issues/3247>`_)
+
+- Fix reference cycle generated when using the ``request`` fixture. (`#3249
+  <https://github.com/pytest-dev/pytest/issues/3249>`_)
+
+- ``[tool:pytest]`` sections in ``*.cfg`` files passed by the ``-c`` option are
+  now properly recognized. (`#3260
+  <https://github.com/pytest-dev/pytest/issues/3260>`_)
+
+
+Improved Documentation
+----------------------
+
+- Add logging plugin to plugins list. (`#3209
+  <https://github.com/pytest-dev/pytest/issues/3209>`_)
+
+
+Trivial/Internal Changes
+------------------------
+
+- Fix minor typo in fixture.rst (`#3259
+  <https://github.com/pytest-dev/pytest/issues/3259>`_)
+
+
+Pytest 3.4.1 (2018-02-20)
+=========================
+
+Bug Fixes
+---------
+
+- Move import of ``doctest.UnexpectedException`` to top-level to avoid possible
+  errors when using ``--pdb``. (`#1810
+  <https://github.com/pytest-dev/pytest/issues/1810>`_)
+
+- Added printing of captured stdout/stderr before entering pdb, and improved a
+  test which was giving false negatives about output capturing. (`#3052
+  <https://github.com/pytest-dev/pytest/issues/3052>`_)
+
+- Fix ordering of tests using parametrized fixtures which can lead to fixtures
+  being created more than necessary. (`#3161
+  <https://github.com/pytest-dev/pytest/issues/3161>`_)
+
+- Fix bug where logging happening at hooks outside of "test run" hooks would
+  cause an internal error. (`#3184
+  <https://github.com/pytest-dev/pytest/issues/3184>`_)
+
+- Detect arguments injected by ``unittest.mock.patch`` decorator correctly when
+  pypi ``mock.patch`` is installed and imported. (`#3206
+  <https://github.com/pytest-dev/pytest/issues/3206>`_)
+
+- Errors shown when a ``pytest.raises()`` with ``match=`` fails are now cleaner
+  on what happened: When no exception was raised, the "matching '...'" part got
+  removed as it falsely implies that an exception was raised but it didn't
+  match. When a wrong exception was raised, it's now thrown (like
+  ``pytest.raised()`` without ``match=`` would) instead of complaining about
+  the unmatched text. (`#3222
+  <https://github.com/pytest-dev/pytest/issues/3222>`_)
+
+- Fixed output capture handling in doctests on macOS. (`#985
+  <https://github.com/pytest-dev/pytest/issues/985>`_)
+
+
+Improved Documentation
+----------------------
+
+- Add Sphinx parameter docs for ``match`` and ``message`` args to
+  ``pytest.raises``. (`#3202
+  <https://github.com/pytest-dev/pytest/issues/3202>`_)
+
+
+Trivial/Internal Changes
+------------------------
+
+- pytest has changed the publication procedure and is now being published to
+  PyPI directly from Travis. (`#3060
+  <https://github.com/pytest-dev/pytest/issues/3060>`_)
+
+- Rename ``ParameterSet._for_parameterize()`` to ``_for_parametrize()`` in
+  order to comply with the naming convention. (`#3166
+  <https://github.com/pytest-dev/pytest/issues/3166>`_)
+
+- Skip failing pdb/doctest test on mac. (`#985
+  <https://github.com/pytest-dev/pytest/issues/985>`_)
+
+
+Pytest 3.4.0 (2018-01-30)
+=========================
+
+Deprecations and Removals
+-------------------------
+
+- All pytest classes now subclass ``object`` for better Python 2/3 compatibility.
+  This should not affect user code except in very rare edge cases. (`#2147
+  <https://github.com/pytest-dev/pytest/issues/2147>`_)
+
+
+Features
+--------
+
+- Introduce ``empty_parameter_set_mark`` ini option to select which mark to
+  apply when ``@pytest.mark.parametrize`` is given an empty set of parameters.
+  Valid options are ``skip`` (default) and ``xfail``. Note that it is planned
+  to change the default to ``xfail`` in future releases as this is considered
+  less error prone. (`#2527
+  <https://github.com/pytest-dev/pytest/issues/2527>`_)
+
+- **Incompatible change**: after community feedback the `logging
+  <https://docs.pytest.org/en/latest/logging.html>`_ functionality has
+  undergone some changes. Please consult the `logging documentation
+  <https://docs.pytest.org/en/latest/logging.html#incompatible-changes-in-pytest-3-4>`_
+  for details. (`#3013 <https://github.com/pytest-dev/pytest/issues/3013>`_)
+
+- Console output falls back to "classic" mode when capturing is disabled (``-s``),
+  otherwise the output gets garbled to the point of being useless. (`#3038
+  <https://github.com/pytest-dev/pytest/issues/3038>`_)
+
+- New `pytest_runtest_logfinish
+  <https://docs.pytest.org/en/latest/writing_plugins.html#_pytest.hookspec.pytest_runtest_logfinish>`_
+  hook which is called when a test item has finished executing, analogous to
+  `pytest_runtest_logstart
+  <https://docs.pytest.org/en/latest/writing_plugins.html#_pytest.hookspec.pytest_runtest_start>`_.
+  (`#3101 <https://github.com/pytest-dev/pytest/issues/3101>`_)
+
+- Improve performance when collecting tests using many fixtures. (`#3107
+  <https://github.com/pytest-dev/pytest/issues/3107>`_)
+
+- New ``caplog.get_records(when)`` method which provides access to the captured
+  records for the ``"setup"``, ``"call"`` and ``"teardown"``
+  testing stages. (`#3117 <https://github.com/pytest-dev/pytest/issues/3117>`_)
+
+- New fixture ``record_xml_attribute`` that allows modifying and inserting
+  attributes on the ``<testcase>`` xml node in JUnit reports. (`#3130
+  <https://github.com/pytest-dev/pytest/issues/3130>`_)
+
+- The default cache directory has been renamed from ``.cache`` to
+  ``.pytest_cache`` after community feedback that the name ``.cache`` did not
+  make it clear that it was used by pytest. (`#3138
+  <https://github.com/pytest-dev/pytest/issues/3138>`_)
+
+- Colorize the levelname column in the live-log output. (`#3142
+  <https://github.com/pytest-dev/pytest/issues/3142>`_)
+
+
+Bug Fixes
+---------
+
+- Fix hanging pexpect test on MacOS by using flush() instead of wait().
+  (`#2022 <https://github.com/pytest-dev/pytest/issues/2022>`_)
+
+- Fix restoring Python state after in-process pytest runs with the
+  ``pytester`` plugin; this may break tests using multiple inprocess
+  pytest runs if later ones depend on earlier ones leaking global interpreter
+  changes. (`#3016 <https://github.com/pytest-dev/pytest/issues/3016>`_)
+
+- Fix skipping plugin reporting hook when test aborted before plugin setup
+  hook. (`#3074 <https://github.com/pytest-dev/pytest/issues/3074>`_)
+
+- Fix progress percentage reported when tests fail during teardown. (`#3088
+  <https://github.com/pytest-dev/pytest/issues/3088>`_)
+
+- **Incompatible change**: ``-o/--override`` option no longer eats all the
+  remaining options, which can lead to surprising behavior: for example,
+  ``pytest -o foo=1 /path/to/test.py`` would fail because ``/path/to/test.py``
+  would be considered as part of the ``-o`` command-line argument. One
+  consequence of this is that now multiple configuration overrides need
+  multiple ``-o`` flags: ``pytest -o foo=1 -o bar=2``. (`#3103
+  <https://github.com/pytest-dev/pytest/issues/3103>`_)
+
+
+Improved Documentation
+----------------------
+
+- Document hooks (defined with ``historic=True``) which cannot be used with
+  ``hookwrapper=True``. (`#2423
+  <https://github.com/pytest-dev/pytest/issues/2423>`_)
+
+- Clarify that warning capturing doesn't change the warning filter by default.
+  (`#2457 <https://github.com/pytest-dev/pytest/issues/2457>`_)
+
+- Clarify a possible confusion when using pytest_fixture_setup with fixture
+  functions that return None. (`#2698
+  <https://github.com/pytest-dev/pytest/issues/2698>`_)
+
+- Fix the wording of a sentence on doctest flags used in pytest. (`#3076
+  <https://github.com/pytest-dev/pytest/issues/3076>`_)
+
+- Prefer ``https://*.readthedocs.io`` over ``http://*.rtfd.org`` for links in
+  the documentation. (`#3092
+  <https://github.com/pytest-dev/pytest/issues/3092>`_)
+
+- Improve readability (wording, grammar) of Getting Started guide (`#3131
+  <https://github.com/pytest-dev/pytest/issues/3131>`_)
+
+- Added note that calling pytest.main multiple times from the same process is
+  not recommended because of import caching. (`#3143
+  <https://github.com/pytest-dev/pytest/issues/3143>`_)
+
+
+Trivial/Internal Changes
+------------------------
+
+- Show a simple and easy error when keyword expressions trigger a syntax error
+  (for example, ``"-k foo and import"`` will show an error that you can not use
+  the ``import`` keyword in expressions). (`#2953
+  <https://github.com/pytest-dev/pytest/issues/2953>`_)
+
+- Change parametrized automatic test id generation to use the ``__name__``
+  attribute of functions instead of the fallback argument name plus counter.
+  (`#2976 <https://github.com/pytest-dev/pytest/issues/2976>`_)
+
+- Replace py.std with stdlib imports. (`#3067
+  <https://github.com/pytest-dev/pytest/issues/3067>`_)
+
+- Corrected 'you' to 'your' in logging docs. (`#3129
+  <https://github.com/pytest-dev/pytest/issues/3129>`_)
+
+
+Pytest 3.3.2 (2017-12-25)
+=========================
+
+Bug Fixes
+---------
+
+- pytester: ignore files used to obtain current user metadata in the fd leak
+  detector. (`#2784 <https://github.com/pytest-dev/pytest/issues/2784>`_)
+
+- Fix **memory leak** where objects returned by fixtures were never destructed
+  by the garbage collector. (`#2981
+  <https://github.com/pytest-dev/pytest/issues/2981>`_)
+
+- Fix conversion of pyargs to filename to not convert symlinks on Python 2. (`#2985
+  <https://github.com/pytest-dev/pytest/issues/2985>`_)
+
+- ``PYTEST_DONT_REWRITE`` is now checked for plugins too rather than only for
+  test modules. (`#2995 <https://github.com/pytest-dev/pytest/issues/2995>`_)
+
+
+Improved Documentation
+----------------------
+
+- Add clarifying note about behavior of multiple parametrized arguments (`#3001
+  <https://github.com/pytest-dev/pytest/issues/3001>`_)
+
+
+Trivial/Internal Changes
+------------------------
+
+- Code cleanup. (`#3015 <https://github.com/pytest-dev/pytest/issues/3015>`_,
+  `#3021 <https://github.com/pytest-dev/pytest/issues/3021>`_)
+
+- Clean up code by replacing imports and references of `_ast` to `ast`. (`#3018
+  <https://github.com/pytest-dev/pytest/issues/3018>`_)
+
+
+Pytest 3.3.1 (2017-12-05)
+=========================
+
+Bug Fixes
+---------
+
+- Fix issue about ``-p no:<plugin>`` having no effect. (`#2920
+  <https://github.com/pytest-dev/pytest/issues/2920>`_)
+
+- Fix regression with warnings that contained non-strings in their arguments in
+  Python 2. (`#2956 <https://github.com/pytest-dev/pytest/issues/2956>`_)
+
+- Always escape null bytes when setting ``PYTEST_CURRENT_TEST``. (`#2957
+  <https://github.com/pytest-dev/pytest/issues/2957>`_)
+
+- Fix ``ZeroDivisionError`` when using the ``testmon`` plugin when no tests
+  were actually collected. (`#2971
+  <https://github.com/pytest-dev/pytest/issues/2971>`_)
+
+- Bring back ``TerminalReporter.writer`` as an alias to
+  ``TerminalReporter._tw``. This alias was removed by accident in the ``3.3.0``
+  release. (`#2984 <https://github.com/pytest-dev/pytest/issues/2984>`_)
+
+- The ``pytest-capturelog`` plugin is now also blacklisted, avoiding errors when
+  running pytest with it still installed. (`#3004
+  <https://github.com/pytest-dev/pytest/issues/3004>`_)
+
+
+Improved Documentation
+----------------------
+
+- Fix broken link to plugin ``pytest-localserver``. (`#2963
+  <https://github.com/pytest-dev/pytest/issues/2963>`_)
+
+
+Trivial/Internal Changes
+------------------------
+
+- Update github "bugs" link in ``CONTRIBUTING.rst`` (`#2949
+  <https://github.com/pytest-dev/pytest/issues/2949>`_)
+
+
 Pytest 3.3.0 (2017-11-23)
 =========================
 
 Deprecations and Removals
 -------------------------
 
 - Pytest no longer supports Python **2.6** and **3.3**. Those Python versions
   are EOL for some time now and incur maintenance and compatibility costs on
@@ -63,17 +752,17 @@ Features
 
 - Now pytest displays the total progress percentage while running tests. The
   previous output style can be set by configuring the ``console_output_style``
   setting to ``classic``. (`#2657 <https://github.com/pytest-dev/pytest/issues/2657>`_)
 
 - Match ``warns`` signature to ``raises`` by adding ``match`` keyword. (`#2708
   <https://github.com/pytest-dev/pytest/issues/2708>`_)
 
-- Pytest now captures and displays output from the standard `logging` module.
+- Pytest now captures and displays output from the standard ``logging`` module.
   The user can control the logging level to be captured by specifying options
   in ``pytest.ini``, the command line and also during individual tests using
   markers. Also, a ``caplog`` fixture is available that enables users to test
   the captured log during specific tests (similar to ``capsys`` for example).
   For more information, please see the `logging docs
   <https://docs.pytest.org/en/latest/logging.html>`_. This feature was
   introduced by merging the popular `pytest-catchlog
   <https://pypi.org/project/pytest-catchlog/>`_ plugin, thanks to `Thomas Hisch
@@ -110,20 +799,20 @@ Bug Fixes
 - Resume output capturing after ``capsys/capfd.disabled()`` context manager.
   (`#1993 <https://github.com/pytest-dev/pytest/issues/1993>`_)
 
 - ``pytest_fixture_setup`` and ``pytest_fixture_post_finalizer`` hooks are now
   called for all ``conftest.py`` files. (`#2124
   <https://github.com/pytest-dev/pytest/issues/2124>`_)
 
 - If an exception happens while loading a plugin, pytest no longer hides the
-  original traceback. In python2 it will show the original traceback with a new
-  message that explains in which plugin. In python3 it will show 2 canonized
+  original traceback. In Python 2 it will show the original traceback with a new
+  message that explains in which plugin. In Python 3 it will show 2 canonized
   exceptions, the original exception while loading the plugin in addition to an
-  exception that PyTest throws about loading a plugin. (`#2491
+  exception that pytest throws about loading a plugin. (`#2491
   <https://github.com/pytest-dev/pytest/issues/2491>`_)
 
 - ``capsys`` and ``capfd`` can now be used by other fixtures. (`#2709
   <https://github.com/pytest-dev/pytest/issues/2709>`_)
 
 - Internal ``pytester`` plugin properly encodes ``bytes`` arguments to
   ``utf-8``. (`#2738 <https://github.com/pytest-dev/pytest/issues/2738>`_)
 
@@ -688,29 +1377,29 @@ Changes
 * Change junitxml.py to produce reports that comply with Junitxml schema.
   If the same test fails with failure in call and then errors in teardown
   we split testcase element into two, one containing the error and the other
   the failure. (`#2228`_) Thanks to `@kkoukiou`_ for the PR.
 
 * Testcase reports with a ``url`` attribute will now properly write this to junitxml.
   Thanks `@fushi`_ for the PR (`#1874`_).
 
-* Remove common items from dict comparision output when verbosity=1. Also update
+* Remove common items from dict comparison output when verbosity=1. Also update
   the truncation message to make it clearer that pytest truncates all
   assertion messages if verbosity < 2 (`#1512`_).
   Thanks `@mattduck`_ for the PR
 
 * ``--pdbcls`` no longer implies ``--pdb``. This makes it possible to use
   ``addopts=--pdbcls=module.SomeClass`` on ``pytest.ini``. Thanks `@davidszotten`_ for
   the PR (`#1952`_).
 
 * fix `#2013`_: turn RecordedWarning into ``namedtuple``,
   to give it a comprehensible repr while preventing unwarranted modification.
 
-* fix `#2208`_: ensure a iteration limit for _pytest.compat.get_real_func.
+* fix `#2208`_: ensure an iteration limit for _pytest.compat.get_real_func.
   Thanks `@RonnyPfannschmidt`_ for the report and PR.
 
 * Hooks are now verified after collection is complete, rather than right after loading installed plugins. This
   makes it easy to write hooks for plugins which will be loaded during collection, for example using the
   ``pytest_plugins`` special variable (`#1821`_).
   Thanks `@nicoddemus`_ for the PR.
 
 * Modify ``pytest_make_parametrize_id()`` hook to accept ``argname`` as an
@@ -804,17 +1493,17 @@ 3.0.7 (2017-03-14)
 ==================
 
 
 * Fix issue in assertion rewriting breaking due to modules silently discarding
   other modules when importing fails
   Notably, importing the ``anydbm`` module is fixed. (`#2248`_).
   Thanks `@pfhayes`_ for the PR.
 
-* junitxml: Fix problematic case where system-out tag occured twice per testcase
+* junitxml: Fix problematic case where system-out tag occurred twice per testcase
   element in the XML report. Thanks `@kkoukiou`_ for the PR.
 
 * Fix regression, pytest now skips unittest correctly if run with ``--pdb``
   (`#2137`_). Thanks to `@gst`_ for the report and `@mbyt`_ for the PR.
 
 * Ignore exceptions raised from descriptors (e.g. properties) during Python test collection (`#2234`_).
   Thanks to `@bluetech`_.
 
@@ -2400,17 +3089,17 @@ 2.6.1 (2014-08-07)
 
 - fix integration of pytest with unittest.mock.patch decorator when
   it uses the "new" argument.  Thanks Nicolas Delaby for test and PR.
 
 - fix issue with detecting conftest files if the arguments contain
   "::" node id specifications (copy pasted from "-v" output)
 
 - fix issue544 by only removing "@NUM" at the end of "::" separated parts
-  and if the part has an ".py" extension
+  and if the part has a ".py" extension
 
 - don't use py.std import helper, rather import things directly.
   Thanks Bruno Oliveira.
 
 2.6
 ===
 
 - Cache exceptions from fixtures according to their scope (issue 467).
@@ -2671,17 +3360,17 @@ 2.5.0 (2013-12-12)
 
 - avoid one surprising case of marker malfunction/confusion::
 
       @pytest.mark.some(lambda arg: ...)
       def test_function():
 
   would not work correctly because pytest assumes @pytest.mark.some
   gets a function to be decorated already.  We now at least detect if this
-  arg is an lambda and thus the example will work.  Thanks Alex Gaynor
+  arg is a lambda and thus the example will work.  Thanks Alex Gaynor
   for bringing it up.
 
 - xfail a test on pypy that checks wrong encoding/ascii (pypy does
   not error out). fixes issue385.
 
 - internally make varnames() deal with classes's __init__,
   although it's not needed by pytest itself atm.  Also
   fix caching.  Fixes issue376.
@@ -2984,17 +3673,17 @@ 2.3.5 (2013-04-30)
 2.3.4 (2012-11-20)
 ==================
 
 - yielded test functions will now have autouse-fixtures active but
   cannot accept fixtures as funcargs - it's anyway recommended to
   rather use the post-2.0 parametrize features instead of yield, see:
   http://pytest.org/latest/example/parametrize.html
 - fix autouse-issue where autouse-fixtures would not be discovered
-  if defined in a a/conftest.py file and tests in a/tests/test_some.py
+  if defined in an a/conftest.py file and tests in a/tests/test_some.py
 - fix issue226 - LIFO ordering for fixture teardowns
 - fix issue224 - invocations with >256 char arguments now work
 - fix issue91 - add/discuss package/directory level setups in example
 - allow to dynamically define markers via
   item.keywords[...]=assignment integrating with "-m" option
 - make "-k" accept an expressions the same as with "-m" so that one
   can write: -k "name1 or name2" etc.  This is a slight incompatibility
   if you used special syntax like "TestClass.test_method" which you now
@@ -3554,17 +4243,17 @@ 1.3.2 (2010-07-08)
 - fix terminal writing on win32/python2.4
 - py.process.cmdexec() now tries harder to return properly encoded unicode objects
   on all python versions
 - install plain py.test/py.which scripts also for Jython, this helps to
   get canonical script paths in virtualenv situations
 - make path.bestrelpath(path) return ".", note that when calling
   X.bestrelpath the assumption is that X is a directory.
 - make initial conftest discovery ignore "--" prefixed arguments
-- fix resultlog plugin when used in an multicpu/multihost xdist situation
+- fix resultlog plugin when used in a multicpu/multihost xdist situation
   (thanks Jakub Gustak)
 - perform distributed testing related reporting in the xdist-plugin
   rather than having dist-related code in the generic py.test
   distribution
 - fix homedir detection on Windows
 - ship distribute_setup.py version 0.6.13
 
 1.3.1 (2010-05-25)
--- a/testing/web-platform/tests/tools/third_party/pytest/CONTRIBUTING.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/CONTRIBUTING.rst
@@ -43,30 +43,28 @@ If you can write a demonstration test th
 fix the bug itself.
 
 
 .. _fixbugs:
 
 Fix bugs
 --------
 
-Look through the GitHub issues for bugs.  Here is a filter you can use:
-https://github.com/pytest-dev/pytest/labels/type%3A%20bug
+Look through the `GitHub issues for bugs <https://github.com/pytest-dev/pytest/labels/type:%20bug>`_.
 
 :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 a filter you can use:
-https://github.com/pytest-dev/pytest/labels/enhancement
+Look through the `GitHub issues for enhancements <https://github.com/pytest-dev/pytest/labels/type:%20enhancement>`_.
 
 :ref:`Talk <contact>` to developers to find out how you can implement specific
 features.
 
 Write documentation
 -------------------
 
 Pytest could always use more documentation.  What exactly is needed?
@@ -136,17 +134,17 @@ If no contributor strongly objects and t
 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
@@ -159,31 +157,32 @@ As stated, the objective is to share mai
 .. _pull-requests:
 
 Preparing Pull Requests
 -----------------------
 
 Short version
 ~~~~~~~~~~~~~
 
-#. Fork the repository;
-#. Target ``master`` for bugfixes and doc changes;
+#. Fork the repository.
+#. Enable and install `pre-commit <https://pre-commit.com>`_ to ensure style-guides and code checks are followed.
+#. Target ``master`` for bugfixes and doc changes.
 #. Target ``features`` for new features or functionality changes.
-#. Follow **PEP-8**. There's a ``tox`` command to help fixing it: ``tox -e fix-lint``.
+#. Follow **PEP-8** for naming and `black <https://github.com/ambv/black>`_ for formatting.
 #. Tests are run using ``tox``::
 
     tox -e linting,py27,py36
 
    The test environments above are usually enough to cover most cases locally.
 
 #. Write a ``changelog`` entry: ``changelog/2574.bugfix``, use issue id number
    and one of ``bugfix``, ``removal``, ``feature``, ``vendor``, ``doc`` or
    ``trivial`` for the issue type.
 #. Unless your change is a trivial or a documentation fix (e.g., a typo or reword of a small section) please
-   add yourself to the ``AUTHORS`` file, in alphabetical order;
+   add yourself to the ``AUTHORS`` file, in alphabetical order.
 
 
 Long version
 ~~~~~~~~~~~~
 
 What is a "pull request"?  It informs the 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>`_.
@@ -199,30 +198,40 @@ Here is a simple overview, with pytest-s
    fine to use ``pytest`` as your fork repository name because it will live
    under your user.
 
 #. Clone your fork locally using `git <https://git-scm.com/>`_ and create a branch::
 
     $ git clone git@github.com:YOUR_GITHUB_USERNAME/pytest.git
     $ cd pytest
     # 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 
+   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
 
+#. Install `pre-commit <https://pre-commit.com>`_ and its hook on the pytest repo::
+
+     $ pip install --user pre-commit
+     $ pre-commit install
+
+   Afterwards ``pre-commit`` will run whenever you commit.
+
+   https://pre-commit.com/ is a framework for managing and maintaining multi-language pre-commit hooks
+   to ensure code-style and code formatting is consistent.
+
 #. 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/)::
 
     $ pip install tox
 
@@ -231,35 +240,30 @@ Here is a simple overview, with pytest-s
    You need to have Python 2.7 and 3.6 available in your system.  Now
    running tests is as simple as issuing this command::
 
     $ tox -e linting,py27,py36
 
    This command will run tests via the "tox" tool against Python 2.7 and 3.6
    and also perform "lint" coding-style checks.
 
-#. You can now edit your local working copy. Please follow PEP-8.
-
-   You can now make the changes you want and run the tests again as necessary.
-
-   If you have too much linting errors, try running::
-
-    $ tox -e fix-lint
-
-   To fix pep8 related errors.
+#. You can now edit your local working copy and run the tests again as necessary. Please follow PEP-8 for naming.
 
    You can pass different options to ``tox``. For example, to run tests on Python 2.7 and pass options to pytest
    (e.g. enter pdb on failure) to pytest you can do::
 
     $ tox -e py27 -- --pdb
 
    Or to only run tests in a particular test module on Python 3.6::
 
     $ tox -e py36 -- testing/test_config.py
 
+
+   When committing, ``pre-commit`` will re-format the files if necessary.
+
 #. Commit and push once your tests pass and you are happy with your change(s)::
 
     $ git commit -a -m "<commit message>"
     $ git push -u
 
 #. Create a new changelog entry in ``changelog``. The file should be named ``<issueid>.<type>``,
    where *issueid* is the number of the issue related to the change and *type* is one of
    ``bugfix``, ``removal``, ``feature``, ``vendor``, ``doc`` or ``trivial``.
@@ -271,8 +275,20 @@ Here is a simple overview, with pytest-s
     head-fork: YOUR_GITHUB_USERNAME/pytest
     compare: your-branch-name
 
     base-fork: pytest-dev/pytest
     base: master          # if it's a bugfix
     base: features        # if it's a feature
 
 
+Joining the Development Team
+----------------------------
+
+Anyone who has successfully seen through a pull request which did not
+require any extra work from the development team to merge will
+themselves gain commit access if they so wish (if we forget to ask please send a friendly
+reminder).  This does not mean your workflow to contribute changes,
+everyone goes through the same pull-request-and-review process and
+no-one merges their own pull requests unless already approved.  It does however mean you can
+participate in the development process more fully since you can merge
+pull requests from other contributors yourself after having reviewed
+them.
--- a/testing/web-platform/tests/tools/third_party/pytest/HOWTORELEASE.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/HOWTORELEASE.rst
@@ -7,59 +7,43 @@ taking a lot of time to make a new one.
 
 .. important::
 
     pytest releases must be prepared on **Linux** because the docs and examples expect
     to be executed in that platform.
 
 #. Install development dependencies in a virtual environment with::
 
-    pip3 install -r tasks/requirements.txt
+    pip3 install -U -r tasks/requirements.txt
 
 #. Create a branch ``release-X.Y.Z`` with the version for the release.
 
    * **patch releases**: from the latest ``master``;
 
    * **minor releases**: from the latest ``features``; then merge with the latest ``master``;
 
    Ensure your are in a clean work tree.
 
-#. Generate docs, changelog, announcements and upload a package to
-   your ``devpi`` staging server::
+#. Generate docs, changelog, announcements and a **local** tag::
 
-     invoke generate.pre-release <VERSION> <DEVPI USER> --password <DEVPI PASSWORD>
-
-   If ``--password`` is not given, it is assumed the user is already logged in ``devpi``.
-   If you don't have an account, please ask for one.
+     invoke generate.pre-release <VERSION>
 
 #. Open a PR for this branch targeting ``master``.
 
-#. Test the package
+#. After all tests pass and the PR has been approved, publish to PyPI by pushing the tag::
 
-   * **Manual method**
-
-     Run from multiple machines::
+     git push git@github.com:pytest-dev/pytest.git <VERSION>
 
-       devpi use https://devpi.net/USER/dev
-       devpi test pytest==VERSION
+   Wait for the deploy to complete, then make sure it is `available on PyPI <https://pypi.org/project/pytest>`_.
 
-     Check that tests pass for relevant combinations with::
-
-       devpi list pytest
+#. Send an email announcement with the contents from::
 
-   * **CI servers**
+     doc/en/announce/release-<VERSION>.rst
 
-     Configure a repository as per-instructions on
-     devpi-cloud-test_ to test the package on Travis_ and AppVeyor_.
-     All test environments should pass.
+   To the following mailing lists:
 
-#. Publish to PyPI::
+   * pytest-dev@python.org (all releases)
+   * python-announce-list@python.org (all releases)
+   * testing-in-python@lists.idyll.org (only major/minor releases)
 
-      invoke generate.publish-release <VERSION> <DEVPI USER> <PYPI_NAME>
-
-   where PYPI_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>`_.
+   And announce it on `Twitter <https://twitter.com/>`_ with the ``#pytest`` hashtag.
 
 #. After a minor/major release, merge ``release-X.Y.Z`` into ``master`` and push (or open a PR).
-
-.. _devpi-cloud-test: https://github.com/obestwalter/devpi-cloud-test
-.. _AppVeyor: https://www.appveyor.com/
-.. _Travis: https://travis-ci.org
--- a/testing/web-platform/tests/tools/third_party/pytest/README.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/README.rst
@@ -1,44 +1,51 @@
 .. 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
+    :target: https://pypi.org/project/pytest/
 
-.. image:: https://anaconda.org/conda-forge/pytest/badges/version.svg
+.. image:: https://img.shields.io/conda/vn/conda-forge/pytest.svg
     :target: https://anaconda.org/conda-forge/pytest
 
 .. image:: https://img.shields.io/pypi/pyversions/pytest.svg
-    :target: https://pypi.python.org/pypi/pytest
+    :target: https://pypi.org/project/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
 
+.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
+  :target: https://github.com/ambv/black
+
+.. image:: https://www.codetriage.com/pytest-dev/pytest/badges/users.svg
+    :target: https://www.codetriage.com/pytest-dev/pytest
+
 The ``pytest`` framework makes it easy to write small tests, yet
 scales to support complex functional testing for applications and libraries.
 
 An example of a simple test:
 
 .. code-block:: python
 
     # content of test_sample.py
     def inc(x):
         return x + 1
 
+
     def test_answer():
         assert inc(3) == 5
 
 
 To execute it::
 
     $ pytest
     ============================= test session starts =============================
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/config.py
+++ /dev/null
@@ -1,1400 +0,0 @@
-""" command line options, ini-file and conftest.py processing. """
-from __future__ import absolute_import, division, print_function
-import argparse
-import shlex
-import traceback
-import types
-import warnings
-
-import six
-import py
-# DON't import pytest here because it causes import cycle troubles
-import sys
-import os
-import _pytest._code
-import _pytest.hookspec  # the extension point definitions
-import _pytest.assertion
-from pluggy import PluginManager, HookimplMarker, HookspecMarker
-from _pytest.compat import safe_str
-
-hookimpl = HookimplMarker("pytest")
-hookspec = HookspecMarker("pytest")
-
-# pytest startup
-#
-
-
-class ConftestImportFailure(Exception):
-    def __init__(self, path, excinfo):
-        Exception.__init__(self, path, excinfo)
-        self.path = path
-        self.excinfo = excinfo
-
-    def __str__(self):
-        etype, evalue, etb = self.excinfo
-        formatted = traceback.format_tb(etb)
-        # The level of the tracebacks we want to print is hand crafted :(
-        return repr(evalue) + '\n' + ''.join(formatted[2:])
-
-
-def main(args=None, plugins=None):
-    """ return exit code, after performing an in-process test run.
-
-    :arg args: list of command line arguments.
-
-    :arg plugins: list of plugin objects to be auto-registered during
-                  initialization.
-    """
-    try:
-        try:
-            config = _prepareconfig(args, plugins)
-        except ConftestImportFailure as e:
-            tw = py.io.TerminalWriter(sys.stderr)
-            for line in traceback.format_exception(*e.excinfo):
-                tw.line(line.rstrip(), red=True)
-            tw.line("ERROR: could not load %s\n" % (e.path), red=True)
-            return 4
-        else:
-            try:
-                return config.hook.pytest_cmdline_main(config=config)
-            finally:
-                config._ensure_unconfigure()
-    except UsageError as e:
-        for msg in e.args:
-            sys.stderr.write("ERROR: %s\n" % (msg,))
-        return 4
-
-
-class cmdline:  # compatibility namespace
-    main = staticmethod(main)
-
-
-class UsageError(Exception):
-    """ error in pytest usage or invocation"""
-
-
-class PrintHelp(Exception):
-    """Raised when pytest should print it's help to skip the rest of the
-    argument parsing and validation."""
-    pass
-
-
-def filename_arg(path, optname):
-    """ Argparse type validator for filename arguments.
-
-    :path: path of filename
-    :optname: name of the option
-    """
-    if os.path.isdir(path):
-        raise UsageError("{0} must be a filename, given: {1}".format(optname, path))
-    return path
-
-
-def directory_arg(path, optname):
-    """Argparse type validator for directory arguments.
-
-    :path: path of directory
-    :optname: name of the option
-    """
-    if not os.path.isdir(path):
-        raise UsageError("{0} must be a directory, given: {1}".format(optname, path))
-    return path
-
-
-default_plugins = (
-    "mark main terminal runner python fixtures debugging unittest capture skipping "
-    "tmpdir monkeypatch recwarn pastebin helpconfig nose assertion "
-    "junitxml resultlog doctest cacheprovider freeze_support "
-    "setuponly setupplan warnings logging").split()
-
-
-builtin_plugins = set(default_plugins)
-builtin_plugins.add("pytester")
-
-
-def get_config():
-    # subsequent calls to main will create a fresh instance
-    pluginmanager = PytestPluginManager()
-    config = Config(pluginmanager)
-    for spec in default_plugins:
-        pluginmanager.import_plugin(spec)
-    return config
-
-
-def get_plugin_manager():
-    """
-    Obtain a new instance of the
-    :py:class:`_pytest.config.PytestPluginManager`, with default plugins
-    already loaded.
-
-    This function can be used by integration with other tools, like hooking
-    into pytest to run tests into an IDE.
-    """
-    return get_config().pluginmanager
-
-
-def _prepareconfig(args=None, plugins=None):
-    warning = None
-    if args is None:
-        args = sys.argv[1:]
-    elif isinstance(args, py.path.local):
-        args = [str(args)]
-    elif not isinstance(args, (tuple, list)):
-        if not isinstance(args, str):
-            raise ValueError("not a string or argument list: %r" % (args,))
-        args = shlex.split(args, posix=sys.platform != "win32")
-        from _pytest import deprecated
-        warning = deprecated.MAIN_STR_ARGS
-    config = get_config()
-    pluginmanager = config.pluginmanager
-    try:
-        if plugins:
-            for plugin in plugins:
-                if isinstance(plugin, six.string_types):
-                    pluginmanager.consider_pluginarg(plugin)
-                else:
-                    pluginmanager.register(plugin)
-        if warning:
-            config.warn('C1', warning)
-        return pluginmanager.hook.pytest_cmdline_parse(
-            pluginmanager=pluginmanager, args=args)
-    except BaseException:
-        config._ensure_unconfigure()
-        raise
-
-
-class PytestPluginManager(PluginManager):
-    """
-    Overwrites :py:class:`pluggy.PluginManager <pluggy.PluginManager>` to add pytest-specific
-    functionality:
-
-    * loading plugins from the command line, ``PYTEST_PLUGIN`` env variable and
-      ``pytest_plugins`` global variables found in plugins being loaded;
-    * ``conftest.py`` loading during start-up;
-    """
-
-    def __init__(self):
-        super(PytestPluginManager, self).__init__("pytest", implprefix="pytest_")
-        self._conftest_plugins = set()
-
-        # state related to local conftest plugins
-        self._path2confmods = {}
-        self._conftestpath2mod = {}
-        self._confcutdir = None
-        self._noconftest = False
-        self._duplicatepaths = set()
-
-        self.add_hookspecs(_pytest.hookspec)
-        self.register(self)
-        if os.environ.get('PYTEST_DEBUG'):
-            err = sys.stderr
-            encoding = getattr(err, 'encoding', 'utf8')
-            try:
-                err = py.io.dupfile(err, encoding=encoding)
-            except Exception:
-                pass
-            self.trace.root.setwriter(err.write)
-            self.enable_tracing()
-
-        # Config._consider_importhook will set a real object if required.
-        self.rewrite_hook = _pytest.assertion.DummyRewriteHook()
-
-    def addhooks(self, module_or_class):
-        """
-        .. deprecated:: 2.8
-
-        Use :py:meth:`pluggy.PluginManager.add_hookspecs <PluginManager.add_hookspecs>`
-        instead.
-        """
-        warning = dict(code="I2",
-                       fslocation=_pytest._code.getfslineno(sys._getframe(1)),
-                       nodeid=None,
-                       message="use pluginmanager.add_hookspecs instead of "
-                               "deprecated addhooks() method.")
-        self._warn(warning)
-        return self.add_hookspecs(module_or_class)
-
-    def parse_hookimpl_opts(self, plugin, name):
-        # pytest hooks are always prefixed with pytest_
-        # so we avoid accessing possibly non-readable attributes
-        # (see issue #1073)
-        if not name.startswith("pytest_"):
-            return
-        # ignore some historic special names which can not be hooks anyway
-        if name == "pytest_plugins" or name.startswith("pytest_funcarg__"):
-            return
-
-        method = getattr(plugin, name)
-        opts = super(PytestPluginManager, self).parse_hookimpl_opts(plugin, name)
-        if opts is not None:
-            for name in ("tryfirst", "trylast", "optionalhook", "hookwrapper"):
-                opts.setdefault(name, hasattr(method, name))
-        return opts
-
-    def parse_hookspec_opts(self, module_or_class, name):
-        opts = super(PytestPluginManager, self).parse_hookspec_opts(
-            module_or_class, name)
-        if opts is None:
-            method = getattr(module_or_class, name)
-            if name.startswith("pytest_"):
-                opts = {"firstresult": hasattr(method, "firstresult"),
-                        "historic": hasattr(method, "historic")}
-        return opts
-
-    def register(self, plugin, name=None):
-        if name == 'pytest_catchlog':
-            self._warn('pytest-catchlog plugin has been merged into the core, '
-                       'please remove it from your requirements.')
-            return
-        ret = super(PytestPluginManager, self).register(plugin, name)
-        if ret:
-            self.hook.pytest_plugin_registered.call_historic(
-                kwargs=dict(plugin=plugin, manager=self))
-
-            if isinstance(plugin, types.ModuleType):
-                self.consider_module(plugin)
-        return ret
-
-    def getplugin(self, name):
-        # support deprecated naming because plugins (xdist e.g.) use it
-        return self.get_plugin(name)
-
-    def hasplugin(self, name):
-        """Return True if the plugin with the given name is registered."""
-        return bool(self.get_plugin(name))
-
-    def pytest_configure(self, config):
-        # XXX now that the pluginmanager exposes hookimpl(tryfirst...)
-        # we should remove tryfirst/trylast as markers
-        config.addinivalue_line("markers",
-                                "tryfirst: mark a hook implementation function such that the "
-                                "plugin machinery will try to call it first/as early as possible.")
-        config.addinivalue_line("markers",
-                                "trylast: mark a hook implementation function such that the "
-                                "plugin machinery will try to call it last/as late as possible.")
-
-    def _warn(self, message):
-        kwargs = message if isinstance(message, dict) else {
-            'code': 'I1',
-            'message': message,
-            'fslocation': None,
-            'nodeid': None,
-        }
-        self.hook.pytest_logwarning.call_historic(kwargs=kwargs)
-
-    #
-    # internal API for local conftest plugin handling
-    #
-    def _set_initial_conftests(self, namespace):
-        """ load initial conftest files given a preparsed "namespace".
-            As conftest files may add their own command line options
-            which have arguments ('--my-opt somepath') we might get some
-            false positives.  All builtin and 3rd party plugins will have
-            been loaded, however, so common options will not confuse our logic
-            here.
-        """
-        current = py.path.local()
-        self._confcutdir = current.join(namespace.confcutdir, abs=True) \
-            if namespace.confcutdir else None
-        self._noconftest = namespace.noconftest
-        testpaths = namespace.file_or_dir
-        foundanchor = False
-        for path in testpaths:
-            path = str(path)
-            # remove node-id syntax
-            i = path.find("::")
-            if i != -1:
-                path = path[:i]
-            anchor = current.join(path, abs=1)
-            if exists(anchor):  # we found some file object
-                self._try_load_conftest(anchor)
-                foundanchor = True
-        if not foundanchor:
-            self._try_load_conftest(current)
-
-    def _try_load_conftest(self, anchor):
-        self._getconftestmodules(anchor)
-        # let's also consider test* subdirs
-        if anchor.check(dir=1):
-            for x in anchor.listdir("test*"):
-                if x.check(dir=1):
-                    self._getconftestmodules(x)
-
-    def _getconftestmodules(self, path):
-        if self._noconftest:
-            return []
-        try:
-            return self._path2confmods[path]
-        except KeyError:
-            if path.isfile():
-                clist = self._getconftestmodules(path.dirpath())
-            else:
-                # XXX these days we may rather want to use config.rootdir
-                # and allow users to opt into looking into the rootdir parent
-                # directories instead of requiring to specify confcutdir
-                clist = []
-                for parent in path.parts():
-                    if self._confcutdir and self._confcutdir.relto(parent):
-                        continue
-                    conftestpath = parent.join("conftest.py")
-                    if conftestpath.isfile():
-                        mod = self._importconftest(conftestpath)
-                        clist.append(mod)
-
-            self._path2confmods[path] = clist
-            return clist
-
-    def _rget_with_confmod(self, name, path):
-        modules = self._getconftestmodules(path)
-        for mod in reversed(modules):
-            try:
-                return mod, getattr(mod, name)
-            except AttributeError:
-                continue
-        raise KeyError(name)
-
-    def _importconftest(self, conftestpath):
-        try:
-            return self._conftestpath2mod[conftestpath]
-        except KeyError:
-            pkgpath = conftestpath.pypkgpath()
-            if pkgpath is None:
-                _ensure_removed_sysmodule(conftestpath.purebasename)
-            try:
-                mod = conftestpath.pyimport()
-            except Exception:
-                raise ConftestImportFailure(conftestpath, sys.exc_info())
-
-            self._conftest_plugins.add(mod)
-            self._conftestpath2mod[conftestpath] = mod
-            dirpath = conftestpath.dirpath()
-            if dirpath in self._path2confmods:
-                for path, mods in self._path2confmods.items():
-                    if path and path.relto(dirpath) or path == dirpath:
-                        assert mod not in mods
-                        mods.append(mod)
-            self.trace("loaded conftestmodule %r" % (mod))
-            self.consider_conftest(mod)
-            return mod
-
-    #
-    # API for bootstrapping plugin loading
-    #
-    #
-
-    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:]
-            self.set_blocked(name)
-            if not name.startswith("pytest_"):
-                self.set_blocked("pytest_" + name)
-        else:
-            self.import_plugin(arg)
-
-    def consider_conftest(self, conftestmodule):
-        self.register(conftestmodule, name=conftestmodule.__file__)
-
-    def consider_env(self):
-        self._import_plugin_specs(os.environ.get("PYTEST_PLUGINS"))
-
-    def consider_module(self, mod):
-        self._import_plugin_specs(getattr(mod, 'pytest_plugins', []))
-
-    def _import_plugin_specs(self, spec):
-        plugins = _get_plugin_specs_as_list(spec)
-        for import_spec in plugins:
-            self.import_plugin(import_spec)
-
-    def import_plugin(self, modname):
-        # most often modname refers to builtin modules, e.g. "pytester",
-        # "terminal" or "capture".  Those plugins are registered under their
-        # basename for historic purposes but must be imported with the
-        # _pytest prefix.
-        assert isinstance(modname, (six.text_type, str)), "module name as text required, got %r" % modname
-        modname = str(modname)
-        if self.is_blocked(modname) or self.get_plugin(modname) is not None:
-            return
-        if modname in builtin_plugins:
-            importspec = "_pytest." + modname
-        else:
-            importspec = modname
-        self.rewrite_hook.mark_rewrite(importspec)
-        try:
-            __import__(importspec)
-        except ImportError as e:
-            new_exc_type = ImportError
-            new_exc_message = 'Error importing plugin "%s": %s' % (modname, safe_str(e.args[0]))
-            new_exc = new_exc_type(new_exc_message)
-
-            six.reraise(new_exc_type, new_exc, sys.exc_info()[2])
-
-        except Exception as e:
-            import pytest
-            if not hasattr(pytest, 'skip') or not isinstance(e, pytest.skip.Exception):
-                raise
-            self._warn("skipped plugin %r: %s" % ((modname, e.msg)))
-        else:
-            mod = sys.modules[importspec]
-            self.register(mod, modname)
-
-
-def _get_plugin_specs_as_list(specs):
-    """
-    Parses a list of "plugin specs" and returns a list of plugin names.
-
-    Plugin specs can be given as a list of strings separated by "," or already as a list/tuple in
-    which case it is returned as a list. Specs can also be `None` in which case an
-    empty list is returned.
-    """
-    if specs is not None:
-        if isinstance(specs, str):
-            specs = specs.split(',') if specs else []
-        if not isinstance(specs, (list, tuple)):
-            raise UsageError("Plugin specs must be a ','-separated string or a "
-                             "list/tuple of strings for plugin names. Given: %r" % specs)
-        return list(specs)
-    return []
-
-
-class Parser:
-    """ Parser for command line arguments and ini-file values.
-
-    :ivar extra_info: dict of generic param -> value to display in case
-        there's an error processing the command line arguments.
-    """
-
-    def __init__(self, usage=None, processopt=None):
-        self._anonymous = OptionGroup("custom options", parser=self)
-        self._groups = []
-        self._processopt = processopt
-        self._usage = usage
-        self._inidict = {}
-        self._ininames = []
-        self.extra_info = {}
-
-    def processoption(self, option):
-        if self._processopt:
-            if option.dest:
-                self._processopt(option)
-
-    def getgroup(self, name, description="", after=None):
-        """ get (or create) a named option Group.
-
-        :name: name of the option group.
-        :description: long description for --help output.
-        :after: name of other group, used for ordering --help output.
-
-        The returned group object has an ``addoption`` method with the same
-        signature as :py:func:`parser.addoption
-        <_pytest.config.Parser.addoption>` but will be shown in the
-        respective group in the output of ``pytest. --help``.
-        """
-        for group in self._groups:
-            if group.name == name:
-                return group
-        group = OptionGroup(name, description, parser=self)
-        i = 0
-        for i, grp in enumerate(self._groups):
-            if grp.name == after:
-                break
-        self._groups.insert(i + 1, group)
-        return group
-
-    def addoption(self, *opts, **attrs):
-        """ register a command line option.
-
-        :opts: option names, can be short or long options.
-        :attrs: same attributes which the ``add_option()`` function of the
-           `argparse library
-           <http://docs.python.org/2/library/argparse.html>`_
-           accepts.
-
-        After command line parsing options are available on the pytest config
-        object via ``config.option.NAME`` where ``NAME`` is usually set
-        by passing a ``dest`` attribute, for example
-        ``addoption("--long", dest="NAME", ...)``.
-        """
-        self._anonymous.addoption(*opts, **attrs)
-
-    def parse(self, args, namespace=None):
-        from _pytest._argcomplete import try_argcomplete
-        self.optparser = self._getparser()
-        try_argcomplete(self.optparser)
-        return self.optparser.parse_args([str(x) for x in args], namespace=namespace)
-
-    def _getparser(self):
-        from _pytest._argcomplete import filescompleter
-        optparser = MyOptionParser(self, self.extra_info)
-        groups = self._groups + [self._anonymous]
-        for group in groups:
-            if group.options:
-                desc = group.description or group.name
-                arggroup = optparser.add_argument_group(desc)
-                for option in group.options:
-                    n = option.names()
-                    a = option.attrs()
-                    arggroup.add_argument(*n, **a)
-        # bash like autocompletion for dirs (appending '/')
-        optparser.add_argument(FILE_OR_DIR, nargs='*').completer = filescompleter
-        return optparser
-
-    def parse_setoption(self, args, option, namespace=None):
-        parsedoption = self.parse(args, namespace=namespace)
-        for name, value in parsedoption.__dict__.items():
-            setattr(option, name, value)
-        return getattr(parsedoption, FILE_OR_DIR)
-
-    def parse_known_args(self, args, namespace=None):
-        """parses and returns a namespace object with known arguments at this
-        point.
-        """
-        return self.parse_known_and_unknown_args(args, namespace=namespace)[0]
-
-    def parse_known_and_unknown_args(self, args, namespace=None):
-        """parses and returns a namespace object with known arguments, and
-        the remaining arguments unknown at this point.
-        """
-        optparser = self._getparser()
-        args = [str(x) for x in args]
-        return optparser.parse_known_args(args, namespace=namespace)
-
-    def addini(self, name, help, type=None, default=None):
-        """ register an ini-file option.
-
-        :name: name of the ini-variable
-        :type: type of the variable, can be ``pathlist``, ``args``, ``linelist``
-               or ``bool``.
-        :default: default value if no ini-file option exists but is queried.
-
-        The value of ini-variables can be retrieved via a call to
-        :py:func:`config.getini(name) <_pytest.config.Config.getini>`.
-        """
-        assert type in (None, "pathlist", "args", "linelist", "bool")
-        self._inidict[name] = (help, type, default)
-        self._ininames.append(name)
-
-
-class ArgumentError(Exception):
-    """
-    Raised if an Argument instance is created with invalid or
-    inconsistent arguments.
-    """
-
-    def __init__(self, msg, option):
-        self.msg = msg
-        self.option_id = str(option)
-
-    def __str__(self):
-        if self.option_id:
-            return "option %s: %s" % (self.option_id, self.msg)
-        else:
-            return self.msg
-
-
-class Argument:
-    """class that mimics the necessary behaviour of optparse.Option
-
-    its currently a least effort implementation
-    and ignoring choices and integer prefixes
-    https://docs.python.org/3/library/optparse.html#optparse-standard-option-types
-    """
-    _typ_map = {
-        'int': int,
-        'string': str,
-        'float': float,
-        'complex': complex,
-    }
-
-    def __init__(self, *names, **attrs):
-        """store parms in private vars for use in add_argument"""
-        self._attrs = attrs
-        self._short_opts = []
-        self._long_opts = []
-        self.dest = attrs.get('dest')
-        if '%default' in (attrs.get('help') or ''):
-            warnings.warn(
-                'pytest now uses argparse. "%default" should be'
-                ' changed to "%(default)s" ',
-                DeprecationWarning,
-                stacklevel=3)
-        try:
-            typ = attrs['type']
-        except KeyError:
-            pass
-        else:
-            # this might raise a keyerror as well, don't want to catch that
-            if isinstance(typ, six.string_types):
-                if typ == 'choice':
-                    warnings.warn(
-                        'type argument to addoption() is a string %r.'
-                        ' For parsearg this is optional and when supplied'
-                        ' should be a type.'
-                        ' (options: %s)' % (typ, names),
-                        DeprecationWarning,
-                        stacklevel=3)
-                    # argparse expects a type here take it from
-                    # the type of the first element
-                    attrs['type'] = type(attrs['choices'][0])
-                else:
-                    warnings.warn(
-                        'type argument to addoption() is a string %r.'
-                        ' For parsearg this should be a type.'
-                        ' (options: %s)' % (typ, names),
-                        DeprecationWarning,
-                        stacklevel=3)
-                    attrs['type'] = Argument._typ_map[typ]
-                # used in test_parseopt -> test_parse_defaultgetter
-                self.type = attrs['type']
-            else:
-                self.type = typ
-        try:
-            # attribute existence is tested in Config._processopt
-            self.default = attrs['default']
-        except KeyError:
-            pass
-        self._set_opt_strings(names)
-        if not self.dest:
-            if self._long_opts:
-                self.dest = self._long_opts[0][2:].replace('-', '_')
-            else:
-                try:
-                    self.dest = self._short_opts[0][1:]
-                except IndexError:
-                    raise ArgumentError(
-                        'need a long or short option', self)
-
-    def names(self):
-        return self._short_opts + self._long_opts
-
-    def attrs(self):
-        # update any attributes set by processopt
-        attrs = 'default dest help'.split()
-        if self.dest:
-            attrs.append(self.dest)
-        for attr in attrs:
-            try:
-                self._attrs[attr] = getattr(self, attr)
-            except AttributeError:
-                pass
-        if self._attrs.get('help'):
-            a = self._attrs['help']
-            a = a.replace('%default', '%(default)s')
-            # a = a.replace('%prog', '%(prog)s')
-            self._attrs['help'] = a
-        return self._attrs
-
-    def _set_opt_strings(self, opts):
-        """directly from optparse
-
-        might not be necessary as this is passed to argparse later on"""
-        for opt in opts:
-            if len(opt) < 2:
-                raise ArgumentError(
-                    "invalid option string %r: "
-                    "must be at least two characters long" % opt, self)
-            elif len(opt) == 2:
-                if not (opt[0] == "-" and opt[1] != "-"):
-                    raise ArgumentError(
-                        "invalid short option string %r: "
-                        "must be of the form -x, (x any non-dash char)" % opt,
-                        self)
-                self._short_opts.append(opt)
-            else:
-                if not (opt[0:2] == "--" and opt[2] != "-"):
-                    raise ArgumentError(
-                        "invalid long option string %r: "
-                        "must start with --, followed by non-dash" % opt,
-                        self)
-                self._long_opts.append(opt)
-
-    def __repr__(self):
-        args = []
-        if self._short_opts:
-            args += ['_short_opts: ' + repr(self._short_opts)]
-        if self._long_opts:
-            args += ['_long_opts: ' + repr(self._long_opts)]
-        args += ['dest: ' + repr(self.dest)]
-        if hasattr(self, 'type'):
-            args += ['type: ' + repr(self.type)]
-        if hasattr(self, 'default'):
-            args += ['default: ' + repr(self.default)]
-        return 'Argument({0})'.format(', '.join(args))
-
-
-class OptionGroup:
-    def __init__(self, name, description="", parser=None):
-        self.name = name
-        self.description = description
-        self.options = []
-        self.parser = parser
-
-    def addoption(self, *optnames, **attrs):
-        """ add an option to this group.
-
-        if a shortened version of a long option is specified it will
-        be suppressed in the help. addoption('--twowords', '--two-words')
-        results in help showing '--two-words' only, but --twowords gets
-        accepted **and** the automatic destination is in args.twowords
-        """
-        conflict = set(optnames).intersection(
-            name for opt in self.options for name in opt.names())
-        if conflict:
-            raise ValueError("option names %s already added" % conflict)
-        option = Argument(*optnames, **attrs)
-        self._addoption_instance(option, shortupper=False)
-
-    def _addoption(self, *optnames, **attrs):
-        option = Argument(*optnames, **attrs)
-        self._addoption_instance(option, shortupper=True)
-
-    def _addoption_instance(self, option, shortupper=False):
-        if not shortupper:
-            for opt in option._short_opts:
-                if opt[0] == '-' and opt[1].islower():
-                    raise ValueError("lowercase shortoptions reserved")
-        if self.parser:
-            self.parser.processoption(option)
-        self.options.append(option)
-
-
-class MyOptionParser(argparse.ArgumentParser):
-    def __init__(self, parser, extra_info=None):
-        if not extra_info:
-            extra_info = {}
-        self._parser = parser
-        argparse.ArgumentParser.__init__(self, usage=parser._usage,
-                                         add_help=False, formatter_class=DropShorterLongHelpFormatter)
-        # extra_info is a dict of (param -> value) to display if there's
-        # an usage error to provide more contextual information to the user
-        self.extra_info = extra_info
-
-    def parse_args(self, args=None, namespace=None):
-        """allow splitting of positional arguments"""
-        args, argv = self.parse_known_args(args, namespace)
-        if argv:
-            for arg in argv:
-                if arg and arg[0] == '-':
-                    lines = ['unrecognized arguments: %s' % (' '.join(argv))]
-                    for k, v in sorted(self.extra_info.items()):
-                        lines.append('  %s: %s' % (k, v))
-                    self.error('\n'.join(lines))
-            getattr(args, FILE_OR_DIR).extend(argv)
-        return args
-
-
-class DropShorterLongHelpFormatter(argparse.HelpFormatter):
-    """shorten help for long options that differ only in extra hyphens
-
-    - collapse **long** options that are the same except for extra hyphens
-    - special action attribute map_long_option allows surpressing additional
-      long options
-    - shortcut if there are only two options and one of them is a short one
-    - cache result on action object as this is called at least 2 times
-    """
-
-    def _format_action_invocation(self, action):
-        orgstr = argparse.HelpFormatter._format_action_invocation(self, action)
-        if orgstr and orgstr[0] != '-':  # only optional arguments
-            return orgstr
-        res = getattr(action, '_formatted_action_invocation', None)
-        if res:
-            return res
-        options = orgstr.split(', ')
-        if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):
-            # a shortcut for '-h, --help' or '--abc', '-a'
-            action._formatted_action_invocation = orgstr
-            return orgstr
-        return_list = []
-        option_map = getattr(action, 'map_long_option', {})
-        if option_map is None:
-            option_map = {}
-        short_long = {}
-        for option in options:
-            if len(option) == 2 or option[2] == ' ':
-                continue
-            if not option.startswith('--'):
-                raise ArgumentError('long optional argument without "--": [%s]'
-                                    % (option), self)
-            xxoption = option[2:]
-            if xxoption.split()[0] not in option_map:
-                shortened = xxoption.replace('-', '')
-                if shortened not in short_long or \
-                   len(short_long[shortened]) < len(xxoption):
-                    short_long[shortened] = xxoption
-        # now short_long has been filled out to the longest with dashes
-        # **and** we keep the right option ordering from add_argument
-        for option in options:
-            if len(option) == 2 or option[2] == ' ':
-                return_list.append(option)
-            if option[2:] == short_long.get(option.replace('-', '')):
-                return_list.append(option.replace(' ', '=', 1))
-        action._formatted_action_invocation = ', '.join(return_list)
-        return action._formatted_action_invocation
-
-
-def _ensure_removed_sysmodule(modname):
-    try:
-        del sys.modules[modname]
-    except KeyError:
-        pass
-
-
-class CmdOptions(object):
-    """ holds cmdline options as attributes."""
-
-    def __init__(self, values=()):
-        self.__dict__.update(values)
-
-    def __repr__(self):
-        return "<CmdOptions %r>" % (self.__dict__,)
-
-    def copy(self):
-        return CmdOptions(self.__dict__)
-
-
-class Notset:
-    def __repr__(self):
-        return "<NOTSET>"
-
-
-notset = Notset()
-FILE_OR_DIR = 'file_or_dir'
-
-
-def _iter_rewritable_modules(package_files):
-    for fn in package_files:
-        is_simple_module = '/' not in fn and fn.endswith('.py')
-        is_package = fn.count('/') == 1 and fn.endswith('__init__.py')
-        if is_simple_module:
-            module_name, _ = os.path.splitext(fn)
-            yield module_name
-        elif is_package:
-            package_name = os.path.dirname(fn)
-            yield package_name
-
-
-class Config(object):
-    """ access to configuration values, pluginmanager and plugin hooks.  """
-
-    def __init__(self, pluginmanager):
-        #: access to command line option as attributes.
-        #: (deprecated), use :py:func:`getoption() <_pytest.config.Config.getoption>` instead
-        self.option = CmdOptions()
-        _a = FILE_OR_DIR
-        self._parser = Parser(
-            usage="%%(prog)s [options] [%s] [%s] [...]" % (_a, _a),
-            processopt=self._processopt,
-        )
-        #: a pluginmanager instance
-        self.pluginmanager = pluginmanager
-        self.trace = self.pluginmanager.trace.root.get("config")
-        self.hook = self.pluginmanager.hook
-        self._inicache = {}
-        self._override_ini = ()
-        self._opt2dest = {}
-        self._cleanup = []
-        self._warn = self.pluginmanager._warn
-        self.pluginmanager.register(self, "pytestconfig")
-        self._configured = False
-
-        def do_setns(dic):
-            import pytest
-            setns(pytest, dic)
-
-        self.hook.pytest_namespace.call_historic(do_setns, {})
-        self.hook.pytest_addoption.call_historic(kwargs=dict(parser=self._parser))
-
-    def add_cleanup(self, func):
-        """ Add a function to be called when the config object gets out of
-        use (usually coninciding with pytest_unconfigure)."""
-        self._cleanup.append(func)
-
-    def _do_configure(self):
-        assert not self._configured
-        self._configured = True
-        self.hook.pytest_configure.call_historic(kwargs=dict(config=self))
-
-    def _ensure_unconfigure(self):
-        if self._configured:
-            self._configured = False
-            self.hook.pytest_unconfigure(config=self)
-            self.hook.pytest_configure._call_history = []
-        while self._cleanup:
-            fin = self._cleanup.pop()
-            fin()
-
-    def warn(self, code, message, fslocation=None, nodeid=None):
-        """ generate a warning for this test session. """
-        self.hook.pytest_logwarning.call_historic(kwargs=dict(
-            code=code, message=message,
-            fslocation=fslocation, nodeid=nodeid))
-
-    def get_terminal_writer(self):
-        return self.pluginmanager.get_plugin("terminalreporter")._tw
-
-    def pytest_cmdline_parse(self, pluginmanager, args):
-        # REF1 assert self == pluginmanager.config, (self, pluginmanager.config)
-        self.parse(args)
-        return self
-
-    def notify_exception(self, excinfo, option=None):
-        if option and option.fulltrace:
-            style = "long"
-        else:
-            style = "native"
-        excrepr = excinfo.getrepr(funcargs=True,
-                                  showlocals=getattr(option, 'showlocals', False),
-                                  style=style,
-                                  )
-        res = self.hook.pytest_internalerror(excrepr=excrepr,
-                                             excinfo=excinfo)
-        if not any(res):
-            for line in str(excrepr).split("\n"):
-                sys.stderr.write("INTERNALERROR> %s\n" % line)
-                sys.stderr.flush()
-
-    def cwd_relative_nodeid(self, nodeid):
-        # nodeid's are relative to the rootpath, compute relative to cwd
-        if self.invocation_dir != self.rootdir:
-            fullpath = self.rootdir.join(nodeid)
-            nodeid = self.invocation_dir.bestrelpath(fullpath)
-        return nodeid
-
-    @classmethod
-    def fromdictargs(cls, option_dict, args):
-        """ constructor useable for subprocesses. """
-        config = get_config()
-        config.option.__dict__.update(option_dict)
-        config.parse(args, addopts=False)
-        for x in config.option.plugins:
-            config.pluginmanager.consider_pluginarg(x)
-        return config
-
-    def _processopt(self, opt):
-        for name in opt._short_opts + opt._long_opts:
-            self._opt2dest[name] = opt.dest
-
-        if hasattr(opt, 'default') and opt.dest:
-            if not hasattr(self.option, opt.dest):
-                setattr(self.option, opt.dest, opt.default)
-
-    @hookimpl(trylast=True)
-    def pytest_load_initial_conftests(self, early_config):
-        self.pluginmanager._set_initial_conftests(early_config.known_args_namespace)
-
-    def _initini(self, args):
-        ns, unknown_args = self._parser.parse_known_and_unknown_args(args, namespace=self.option.copy())
-        r = determine_setup(ns.inifilename, ns.file_or_dir + unknown_args, warnfunc=self.warn)
-        self.rootdir, self.inifile, self.inicfg = r
-        self._parser.extra_info['rootdir'] = self.rootdir
-        self._parser.extra_info['inifile'] = self.inifile
-        self.invocation_dir = py.path.local()
-        self._parser.addini('addopts', 'extra command line options', 'args')
-        self._parser.addini('minversion', 'minimally required pytest version')
-        self._override_ini = ns.override_ini or ()
-
-    def _consider_importhook(self, args):
-        """Install the PEP 302 import hook if using assertion rewriting.
-
-        Needs to parse the --assert=<mode> option from the commandline
-        and find all the installed plugins to mark them for rewriting
-        by the importhook.
-        """
-        ns, unknown_args = self._parser.parse_known_and_unknown_args(args)
-        mode = ns.assertmode
-        if mode == 'rewrite':
-            try:
-                hook = _pytest.assertion.install_importhook(self)
-            except SystemError:
-                mode = 'plain'
-            else:
-                self._mark_plugins_for_rewrite(hook)
-        self._warn_about_missing_assertion(mode)
-
-    def _mark_plugins_for_rewrite(self, hook):
-        """
-        Given an importhook, mark for rewrite any top-level
-        modules or packages in the distribution package for
-        all pytest plugins.
-        """
-        import pkg_resources
-        self.pluginmanager.rewrite_hook = hook
-
-        # 'RECORD' available for plugins installed normally (pip install)
-        # 'SOURCES.txt' available for plugins installed in dev mode (pip install -e)
-        # for installed plugins 'SOURCES.txt' returns an empty list, and vice-versa
-        # so it shouldn't be an issue
-        metadata_files = 'RECORD', 'SOURCES.txt'
-
-        package_files = (
-            entry.split(',')[0]
-            for entrypoint in pkg_resources.iter_entry_points('pytest11')
-            for metadata in metadata_files
-            for entry in entrypoint.dist._get_metadata(metadata)
-        )
-
-        for name in _iter_rewritable_modules(package_files):
-            hook.mark_rewrite(name)
-
-    def _warn_about_missing_assertion(self, mode):
-        try:
-            assert False
-        except AssertionError:
-            pass
-        else:
-            if mode == 'plain':
-                sys.stderr.write("WARNING: ASSERTIONS ARE NOT EXECUTED"
-                                 " and FAILING TESTS WILL PASS.  Are you"
-                                 " using python -O?")
-            else:
-                sys.stderr.write("WARNING: assertions not in test modules or"
-                                 " plugins will be ignored"
-                                 " because assert statements are not executed "
-                                 "by the underlying Python interpreter "
-                                 "(are you using python -O?)\n")
-
-    def _preparse(self, args, addopts=True):
-        if addopts:
-            args[:] = shlex.split(os.environ.get('PYTEST_ADDOPTS', '')) + args
-        self._initini(args)
-        if addopts:
-            args[:] = self.getini("addopts") + args
-        self._checkversion()
-        self._consider_importhook(args)
-        self.pluginmanager.consider_preparse(args)
-        self.pluginmanager.load_setuptools_entrypoints('pytest11')
-        self.pluginmanager.consider_env()
-        self.known_args_namespace = ns = self._parser.parse_known_args(args, namespace=self.option.copy())
-        if self.known_args_namespace.confcutdir is None and self.inifile:
-            confcutdir = py.path.local(self.inifile).dirname
-            self.known_args_namespace.confcutdir = confcutdir
-        try:
-            self.hook.pytest_load_initial_conftests(early_config=self,
-                                                    args=args, parser=self._parser)
-        except ConftestImportFailure:
-            e = sys.exc_info()[1]
-            if ns.help or ns.version:
-                # we don't want to prevent --help/--version to work
-                # so just let is pass and print a warning at the end
-                self._warn("could not load initial conftests (%s)\n" % e.path)
-            else:
-                raise
-
-    def _checkversion(self):
-        import pytest
-        minver = self.inicfg.get('minversion', None)
-        if minver:
-            ver = minver.split(".")
-            myver = pytest.__version__.split(".")
-            if myver < ver:
-                raise pytest.UsageError(
-                    "%s:%d: requires pytest-%s, actual pytest-%s'" % (
-                        self.inicfg.config.path, self.inicfg.lineof('minversion'),
-                        minver, pytest.__version__))
-
-    def parse(self, args, addopts=True):
-        # parse given cmdline arguments into this config object.
-        assert not hasattr(self, 'args'), (
-            "can only parse cmdline args at most once per Config object")
-        self._origargs = args
-        self.hook.pytest_addhooks.call_historic(
-            kwargs=dict(pluginmanager=self.pluginmanager))
-        self._preparse(args, addopts=addopts)
-        # XXX deprecated hook:
-        self.hook.pytest_cmdline_preparse(config=self, args=args)
-        self._parser.after_preparse = True
-        try:
-            args = self._parser.parse_setoption(args, self.option, namespace=self.option)
-            if not args:
-                cwd = os.getcwd()
-                if cwd == self.rootdir:
-                    args = self.getini('testpaths')
-                if not args:
-                    args = [cwd]
-            self.args = args
-        except PrintHelp:
-            pass
-
-    def addinivalue_line(self, name, line):
-        """ add a line to an ini-file option. The option must have been
-        declared but might not yet be set in which case the line becomes the
-        the first line in its value. """
-        x = self.getini(name)
-        assert isinstance(x, list)
-        x.append(line)  # modifies the cached list inline
-
-    def getini(self, name):
-        """ return configuration value from an :ref:`ini file <inifiles>`. If the
-        specified name hasn't been registered through a prior
-        :py:func:`parser.addini <_pytest.config.Parser.addini>`
-        call (usually from a plugin), a ValueError is raised. """
-        try:
-            return self._inicache[name]
-        except KeyError:
-            self._inicache[name] = val = self._getini(name)
-            return val
-
-    def _getini(self, name):
-        try:
-            description, type, default = self._parser._inidict[name]
-        except KeyError:
-            raise ValueError("unknown configuration value: %r" % (name,))
-        value = self._get_override_ini_value(name)
-        if value is None:
-            try:
-                value = self.inicfg[name]
-            except KeyError:
-                if default is not None:
-                    return default
-                if type is None:
-                    return ''
-                return []
-        if type == "pathlist":
-            dp = py.path.local(self.inicfg.config.path).dirpath()
-            values = []
-            for relpath in shlex.split(value):
-                values.append(dp.join(relpath, abs=True))
-            return values
-        elif type == "args":
-            return shlex.split(value)
-        elif type == "linelist":
-            return [t for t in map(lambda x: x.strip(), value.split("\n")) if t]
-        elif type == "bool":
-            return bool(_strtobool(value.strip()))
-        else:
-            assert type is None
-            return value
-
-    def _getconftest_pathlist(self, name, path):
-        try:
-            mod, relroots = self.pluginmanager._rget_with_confmod(name, path)
-        except KeyError:
-            return None
-        modpath = py.path.local(mod.__file__).dirpath()
-        values = []
-        for relroot in relroots:
-            if not isinstance(relroot, py.path.local):
-                relroot = relroot.replace("/", py.path.local.sep)
-                relroot = modpath.join(relroot, abs=True)
-            values.append(relroot)
-        return values
-
-    def _get_override_ini_value(self, name):
-        value = None
-        # override_ini is a list of list, to support both -o foo1=bar1 foo2=bar2 and
-        # and -o foo1=bar1 -o foo2=bar2 options
-        # always use the last item if multiple value set for same ini-name,
-        # e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2
-        for ini_config_list in self._override_ini:
-            for ini_config in ini_config_list:
-                try:
-                    (key, user_ini_value) = ini_config.split("=", 1)
-                except ValueError:
-                    raise UsageError("-o/--override-ini expects option=value style.")
-                if key == name:
-                    value = user_ini_value
-        return value
-
-    def getoption(self, name, default=notset, skip=False):
-        """ return command line option value.
-
-        :arg name: name of the option.  You may also specify
-            the literal ``--OPT`` option instead of the "dest" option name.
-        :arg default: default value if no option of that name exists.
-        :arg skip: if True raise pytest.skip if option does not exists
-            or has a None value.
-        """
-        name = self._opt2dest.get(name, name)
-        try:
-            val = getattr(self.option, name)
-            if val is None and skip:
-                raise AttributeError(name)
-            return val
-        except AttributeError:
-            if default is not notset:
-                return default
-            if skip:
-                import pytest
-                pytest.skip("no %r option found" % (name,))
-            raise ValueError("no option named %r" % (name,))
-
-    def getvalue(self, name, path=None):
-        """ (deprecated, use getoption()) """
-        return self.getoption(name)
-
-    def getvalueorskip(self, name, path=None):
-        """ (deprecated, use getoption(skip=True)) """
-        return self.getoption(name, skip=True)
-
-
-def exists(path, ignore=EnvironmentError):
-    try:
-        return path.check()
-    except ignore:
-        return False
-
-
-def getcfg(args, warnfunc=None):
-    """
-    Search the list of arguments for a valid ini-file for pytest,
-    and return a tuple of (rootdir, inifile, cfg-dict).
-
-    note: warnfunc is an optional function used to warn
-        about ini-files that use deprecated features.
-        This parameter should be removed when pytest
-        adopts standard deprecation warnings (#1804).
-    """
-    from _pytest.deprecated import SETUP_CFG_PYTEST
-    inibasenames = ["pytest.ini", "tox.ini", "setup.cfg"]
-    args = [x for x in args if not str(x).startswith("-")]
-    if not args:
-        args = [py.path.local()]
-    for arg in args:
-        arg = py.path.local(arg)
-        for base in arg.parts(reverse=True):
-            for inibasename in inibasenames:
-                p = base.join(inibasename)
-                if exists(p):
-                    iniconfig = py.iniconfig.IniConfig(p)
-                    if 'pytest' in iniconfig.sections:
-                        if inibasename == 'setup.cfg' and warnfunc:
-                            warnfunc('C1', SETUP_CFG_PYTEST)
-                        return base, p, iniconfig['pytest']
-                    if inibasename == 'setup.cfg' and 'tool:pytest' in iniconfig.sections:
-                        return base, p, iniconfig['tool:pytest']
-                    elif inibasename == "pytest.ini":
-                        # allowed to be empty
-                        return base, p, {}
-    return None, None, None
-
-
-def get_common_ancestor(paths):
-    common_ancestor = None
-    for path in paths:
-        if not path.exists():
-            continue
-        if common_ancestor is None:
-            common_ancestor = path
-        else:
-            if path.relto(common_ancestor) or path == common_ancestor:
-                continue
-            elif common_ancestor.relto(path):
-                common_ancestor = path
-            else:
-                shared = path.common(common_ancestor)
-                if shared is not None:
-                    common_ancestor = shared
-    if common_ancestor is None:
-        common_ancestor = py.path.local()
-    elif common_ancestor.isfile():
-        common_ancestor = common_ancestor.dirpath()
-    return common_ancestor
-
-
-def get_dirs_from_args(args):
-    def is_option(x):
-        return str(x).startswith('-')
-
-    def get_file_part_from_node_id(x):
-        return str(x).split('::')[0]
-
-    def get_dir_from_path(path):
-        if path.isdir():
-            return path
-        return py.path.local(path.dirname)
-
-    # These look like paths but may not exist
-    possible_paths = (
-        py.path.local(get_file_part_from_node_id(arg))
-        for arg in args
-        if not is_option(arg)
-    )
-
-    return [
-        get_dir_from_path(path)
-        for path in possible_paths
-        if path.exists()
-    ]
-
-
-def determine_setup(inifile, args, warnfunc=None):
-    dirs = get_dirs_from_args(args)
-    if inifile:
-        iniconfig = py.iniconfig.IniConfig(inifile)
-        try:
-            inicfg = iniconfig["pytest"]
-        except KeyError:
-            inicfg = None
-        rootdir = get_common_ancestor(dirs)
-    else:
-        ancestor = get_common_ancestor(dirs)
-        rootdir, inifile, inicfg = getcfg([ancestor], warnfunc=warnfunc)
-        if rootdir is None:
-            for rootdir in ancestor.parts(reverse=True):
-                if rootdir.join("setup.py").exists():
-                    break
-            else:
-                rootdir, inifile, inicfg = getcfg(dirs, warnfunc=warnfunc)
-                if rootdir is None:
-                    rootdir = get_common_ancestor([py.path.local(), ancestor])
-                    is_fs_root = os.path.splitdrive(str(rootdir))[1] == '/'
-                    if is_fs_root:
-                        rootdir = ancestor
-    return rootdir, inifile, inicfg or {}
-
-
-def setns(obj, dic):
-    import pytest
-    for name, value in dic.items():
-        if isinstance(value, dict):
-            mod = getattr(obj, name, None)
-            if mod is None:
-                modname = "pytest.%s" % name
-                mod = types.ModuleType(modname)
-                sys.modules[modname] = mod
-                mod.__all__ = []
-                setattr(obj, name, mod)
-            obj.__all__.append(name)
-            setns(mod, value)
-        else:
-            setattr(obj, name, value)
-            obj.__all__.append(name)
-            # if obj != pytest:
-            #    pytest.__all__.append(name)
-            setattr(pytest, name, value)
-
-
-def create_terminal_writer(config, *args, **kwargs):
-    """Create a TerminalWriter instance configured according to the options
-    in the config object. Every code which requires a TerminalWriter object
-    and has access to a config object should use this function.
-    """
-    tw = py.io.TerminalWriter(*args, **kwargs)
-    if config.option.color == 'yes':
-        tw.hasmarkup = True
-    if config.option.color == 'no':
-        tw.hasmarkup = False
-    return tw
-
-
-def _strtobool(val):
-    """Convert a string representation of truth to true (1) or false (0).
-
-    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
-    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
-    'val' is anything else.
-
-    .. note:: copied from distutils.util
-    """
-    val = val.lower()
-    if val in ('y', 'yes', 't', 'true', 'on', '1'):
-        return 1
-    elif val in ('n', 'no', 'f', 'false', 'off', '0'):
-        return 0
-    else:
-        raise ValueError("invalid truth value %r" % (val,))
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/mark.py
+++ /dev/null
@@ -1,496 +0,0 @@
-""" generic mechanism for marking and selecting python functions. """
-from __future__ import absolute_import, division, print_function
-
-import inspect
-import warnings
-import attr
-from collections import namedtuple
-from operator import attrgetter
-from six.moves import map
-from .deprecated import MARK_PARAMETERSET_UNPACKING
-from .compat import NOTSET, getfslineno
-
-
-def alias(name, warning=None):
-    getter = attrgetter(name)
-
-    def warned(self):
-        warnings.warn(warning, stacklevel=2)
-        return getter(self)
-
-    return property(getter if warning is None else warned, doc='alias for ' + name)
-
-
-class ParameterSet(namedtuple('ParameterSet', 'values, marks, id')):
-    @classmethod
-    def param(cls, *values, **kw):
-        marks = kw.pop('marks', ())
-        if isinstance(marks, MarkDecorator):
-            marks = marks,
-        else:
-            assert isinstance(marks, (tuple, list, set))
-
-        def param_extract_id(id=None):
-            return id
-
-        id = param_extract_id(**kw)
-        return cls(values, marks, id)
-
-    @classmethod
-    def extract_from(cls, parameterset, legacy_force_tuple=False):
-        """
-        :param parameterset:
-            a legacy style parameterset that may or may not be a tuple,
-            and may or may not be wrapped into a mess of mark objects
-
-        :param legacy_force_tuple:
-            enforce tuple wrapping so single argument tuple values
-            don't get decomposed and break tests
-
-        """
-
-        if isinstance(parameterset, cls):
-            return parameterset
-        if not isinstance(parameterset, MarkDecorator) and legacy_force_tuple:
-            return cls.param(parameterset)
-
-        newmarks = []
-        argval = parameterset
-        while isinstance(argval, MarkDecorator):
-            newmarks.append(MarkDecorator(Mark(
-                argval.markname, argval.args[:-1], argval.kwargs)))
-            argval = argval.args[-1]
-        assert not isinstance(argval, ParameterSet)
-        if legacy_force_tuple:
-            argval = argval,
-
-        if newmarks:
-            warnings.warn(MARK_PARAMETERSET_UNPACKING)
-
-        return cls(argval, marks=newmarks, id=None)
-
-    @classmethod
-    def _for_parameterize(cls, argnames, argvalues, function):
-        if not isinstance(argnames, (tuple, list)):
-            argnames = [x.strip() for x in argnames.split(",") if x.strip()]
-            force_tuple = len(argnames) == 1
-        else:
-            force_tuple = False
-        parameters = [
-            ParameterSet.extract_from(x, legacy_force_tuple=force_tuple)
-            for x in argvalues]
-        del argvalues
-
-        if not parameters:
-            fs, lineno = getfslineno(function)
-            reason = "got empty parameter set %r, function %s at %s:%d" % (
-                argnames, function.__name__, fs, lineno)
-            mark = MARK_GEN.skip(reason=reason)
-            parameters.append(ParameterSet(
-                values=(NOTSET,) * len(argnames),
-                marks=[mark],
-                id=None,
-            ))
-        return argnames, parameters
-
-
-class MarkerError(Exception):
-
-    """Error in use of a pytest marker/attribute."""
-
-
-def param(*values, **kw):
-    return ParameterSet.param(*values, **kw)
-
-
-def pytest_addoption(parser):
-    group = parser.getgroup("general")
-    group._addoption(
-        '-k',
-        action="store", dest="keyword", default='', metavar="EXPRESSION",
-        help="only run tests which match the given substring expression. "
-             "An expression is a python evaluatable expression "
-             "where all names are substring-matched against test names "
-             "and their parent classes. Example: -k 'test_method or test_"
-             "other' matches all test functions and classes whose name "
-             "contains 'test_method' or 'test_other', while -k 'not test_method' "
-             "matches those that don't contain 'test_method' in their names. "
-             "Additionally keywords are matched to classes and functions "
-             "containing extra names in their 'extra_keyword_matches' set, "
-             "as well as functions which have names assigned directly to them."
-    )
-
-    group._addoption(
-        "-m",
-        action="store", dest="markexpr", default="", metavar="MARKEXPR",
-        help="only run tests matching given mark expression.  "
-             "example: -m 'mark1 and not mark2'."
-    )
-
-    group.addoption(
-        "--markers", action="store_true",
-        help="show markers (builtin, plugin and per-project ones)."
-    )
-
-    parser.addini("markers", "markers for test functions", 'linelist')
-
-
-def pytest_cmdline_main(config):
-    import _pytest.config
-    if config.option.markers:
-        config._do_configure()
-        tw = _pytest.config.create_terminal_writer(config)
-        for line in config.getini("markers"):
-            parts = line.split(":", 1)
-            name = parts[0]
-            rest = parts[1] if len(parts) == 2 else ''
-            tw.write("@pytest.mark.%s:" % name, bold=True)
-            tw.line(rest)
-            tw.line()
-        config._ensure_unconfigure()
-        return 0
-
-
-pytest_cmdline_main.tryfirst = True
-
-
-def pytest_collection_modifyitems(items, config):
-    keywordexpr = config.option.keyword.lstrip()
-    matchexpr = config.option.markexpr
-    if not keywordexpr and not matchexpr:
-        return
-    # pytest used to allow "-" for negating
-    # but today we just allow "-" at the beginning, use "not" instead
-    # we probably remove "-" altogether soon
-    if keywordexpr.startswith("-"):
-        keywordexpr = "not " + keywordexpr[1:]
-    selectuntil = False
-    if keywordexpr[-1:] == ":":
-        selectuntil = True
-        keywordexpr = keywordexpr[:-1]
-
-    remaining = []
-    deselected = []
-    for colitem in items:
-        if keywordexpr and not matchkeyword(colitem, keywordexpr):
-            deselected.append(colitem)
-        else:
-            if selectuntil:
-                keywordexpr = None
-            if matchexpr:
-                if not matchmark(colitem, matchexpr):
-                    deselected.append(colitem)
-                    continue
-            remaining.append(colitem)
-
-    if deselected:
-        config.hook.pytest_deselected(items=deselected)
-        items[:] = remaining
-
-
-@attr.s
-class MarkMapping(object):
-    """Provides a local mapping for markers where item access
-    resolves to True if the marker is present. """
-
-    own_mark_names = attr.ib()
-
-    @classmethod
-    def from_keywords(cls, keywords):
-        mark_names = set()
-        for key, value in keywords.items():
-            if isinstance(value, MarkInfo) or isinstance(value, MarkDecorator):
-                mark_names.add(key)
-        return cls(mark_names)
-
-    def __getitem__(self, name):
-        return name in self.own_mark_names
-
-
-class KeywordMapping(object):
-    """Provides a local mapping for keywords.
-    Given a list of names, map any substring of one of these names to True.
-    """
-
-    def __init__(self, names):
-        self._names = names
-
-    def __getitem__(self, subname):
-        for name in self._names:
-            if subname in name:
-                return True
-        return False
-
-
-def matchmark(colitem, markexpr):
-    """Tries to match on any marker names, attached to the given colitem."""
-    return eval(markexpr, {}, MarkMapping.from_keywords(colitem.keywords))
-
-
-def matchkeyword(colitem, keywordexpr):
-    """Tries to match given keyword expression to given collector item.
-
-    Will match on the name of colitem, including the names of its parents.
-    Only matches names of items which are either a :class:`Class` or a
-    :class:`Function`.
-    Additionally, matches on names in the 'extra_keyword_matches' set of
-    any item, as well as names directly assigned to test functions.
-    """
-    mapped_names = set()
-
-    # Add the names of the current item and any parent items
-    import pytest
-    for item in colitem.listchain():
-        if not isinstance(item, pytest.Instance):
-            mapped_names.add(item.name)
-
-    # Add the names added as extra keywords to current or parent items
-    for name in colitem.listextrakeywords():
-        mapped_names.add(name)
-
-    # Add the names attached to the current function through direct assignment
-    if hasattr(colitem, 'function'):
-        for name in colitem.function.__dict__:
-            mapped_names.add(name)
-
-    mapping = KeywordMapping(mapped_names)
-    if " " not in keywordexpr:
-        # special case to allow for simple "-k pass" and "-k 1.3"
-        return mapping[keywordexpr]
-    elif keywordexpr.startswith("not ") and " " not in keywordexpr[4:]:
-        return not mapping[keywordexpr[4:]]
-    return eval(keywordexpr, {}, mapping)
-
-
-def pytest_configure(config):
-    config._old_mark_config = MARK_GEN._config
-    if config.option.strict:
-        MARK_GEN._config = config
-
-
-def pytest_unconfigure(config):
-    MARK_GEN._config = getattr(config, '_old_mark_config', None)
-
-
-class MarkGenerator:
-    """ Factory for :class:`MarkDecorator` objects - exposed as
-    a ``pytest.mark`` singleton instance.  Example::
-
-         import pytest
-         @pytest.mark.slowtest
-         def test_function():
-            pass
-
-    will set a 'slowtest' :class:`MarkInfo` object
-    on the ``test_function`` object. """
-    _config = None
-
-    def __getattr__(self, name):
-        if name[0] == "_":
-            raise AttributeError("Marker name must NOT start with underscore")
-        if self._config is not None:
-            self._check(name)
-        return MarkDecorator(Mark(name, (), {}))
-
-    def _check(self, name):
-        try:
-            if name in self._markers:
-                return
-        except AttributeError:
-            pass
-        self._markers = values = set()
-        for line in self._config.getini("markers"):
-            marker = line.split(":", 1)[0]
-            marker = marker.rstrip()
-            x = marker.split("(", 1)[0]
-            values.add(x)
-        if name not in self._markers:
-            raise AttributeError("%r not a registered marker" % (name,))
-
-
-def istestfunc(func):
-    return hasattr(func, "__call__") and \
-        getattr(func, "__name__", "<lambda>") != "<lambda>"
-
-
-@attr.s(frozen=True)
-class Mark(object):
-    name = attr.ib()
-    args = attr.ib()
-    kwargs = attr.ib()
-
-    def combined_with(self, other):
-        assert self.name == other.name
-        return Mark(
-            self.name, self.args + other.args,
-            dict(self.kwargs, **other.kwargs))
-
-
-@attr.s
-class MarkDecorator(object):
-    """ A decorator for test functions and test classes.  When applied
-    it will create :class:`MarkInfo` objects which may be
-    :ref:`retrieved by hooks as item keywords <excontrolskip>`.
-    MarkDecorator instances are often created like this::
-
-        mark1 = pytest.mark.NAME              # simple MarkDecorator
-        mark2 = pytest.mark.NAME(name1=value) # parametrized MarkDecorator
-
-    and can then be applied as decorators to test functions::
-
-        @mark2
-        def test_function():
-            pass
-
-    When a MarkDecorator instance is called it does the following:
-      1. If called with a single class as its only positional argument and no
-         additional keyword arguments, it attaches itself to the class so it
-         gets applied automatically to all test cases found in that class.
-      2. If called with a single function as its only positional argument and
-         no additional keyword arguments, it attaches a MarkInfo object to the
-         function, containing all the arguments already stored internally in
-         the MarkDecorator.
-      3. When called in any other case, it performs a 'fake construction' call,
-         i.e. it returns a new MarkDecorator instance with the original
-         MarkDecorator's content updated with the arguments passed to this
-         call.
-
-    Note: The rules above prevent MarkDecorator objects from storing only a
-    single function or class reference as their positional argument with no
-    additional keyword or positional arguments.
-
-    """
-
-    mark = attr.ib(validator=attr.validators.instance_of(Mark))
-
-    name = alias('mark.name')
-    args = alias('mark.args')
-    kwargs = alias('mark.kwargs')
-
-    @property
-    def markname(self):
-        return self.name  # for backward-compat (2.4.1 had this attr)
-
-    def __eq__(self, other):
-        return self.mark == other.mark if isinstance(other, MarkDecorator) else False
-
-    def __repr__(self):
-        return "<MarkDecorator %r>" % (self.mark,)
-
-    def with_args(self, *args, **kwargs):
-        """ return a MarkDecorator with extra arguments added
-
-        unlike call this can be used even if the sole argument is a callable/class
-
-        :return: MarkDecorator
-        """
-
-        mark = Mark(self.name, args, kwargs)
-        return self.__class__(self.mark.combined_with(mark))
-
-    def __call__(self, *args, **kwargs):
-        """ if passed a single callable argument: decorate it with mark info.
-            otherwise add *args/**kwargs in-place to mark information. """
-        if args and not kwargs:
-            func = args[0]
-            is_class = inspect.isclass(func)
-            if len(args) == 1 and (istestfunc(func) or is_class):
-                if is_class:
-                    store_mark(func, self.mark)
-                else:
-                    store_legacy_markinfo(func, self.mark)
-                    store_mark(func, self.mark)
-                return func
-        return self.with_args(*args, **kwargs)
-
-
-def get_unpacked_marks(obj):
-    """
-    obtain the unpacked marks that are stored on a object
-    """
-    mark_list = getattr(obj, 'pytestmark', [])
-
-    if not isinstance(mark_list, list):
-        mark_list = [mark_list]
-    return [
-        getattr(mark, 'mark', mark)  # unpack MarkDecorator
-        for mark in mark_list
-    ]
-
-
-def store_mark(obj, mark):
-    """store a Mark on a object
-    this is used to implement the Mark declarations/decorators correctly
-    """
-    assert isinstance(mark, Mark), mark
-    # always reassign name to avoid updating pytestmark
-    # in a reference that was only borrowed
-    obj.pytestmark = get_unpacked_marks(obj) + [mark]
-
-
-def store_legacy_markinfo(func, mark):
-    """create the legacy MarkInfo objects and put them onto the function
-    """
-    if not isinstance(mark, Mark):
-        raise TypeError("got {mark!r} instead of a Mark".format(mark=mark))
-    holder = getattr(func, mark.name, None)
-    if holder is None:
-        holder = MarkInfo(mark)
-        setattr(func, mark.name, holder)
-    else:
-        holder.add_mark(mark)
-
-
-class MarkInfo(object):
-    """ Marking object created by :class:`MarkDecorator` instances. """
-
-    def __init__(self, mark):
-        assert isinstance(mark, Mark), repr(mark)
-        self.combined = mark
-        self._marks = [mark]
-
-    name = alias('combined.name')
-    args = alias('combined.args')
-    kwargs = alias('combined.kwargs')
-
-    def __repr__(self):
-        return "<MarkInfo {0!r}>".format(self.combined)
-
-    def add_mark(self, mark):
-        """ add a MarkInfo with the given args and kwargs. """
-        self._marks.append(mark)
-        self.combined = self.combined.combined_with(mark)
-
-    def __iter__(self):
-        """ yield MarkInfo objects each relating to a marking-call. """
-        return map(MarkInfo, self._marks)
-
-
-MARK_GEN = MarkGenerator()
-
-
-def _marked(func, mark):
-    """ Returns True if :func: is already marked with :mark:, False otherwise.
-    This can happen if marker is applied to class and the test file is
-    invoked more than once.
-    """
-    try:
-        func_mark = getattr(func, mark.name)
-    except AttributeError:
-        return False
-    return mark.args == func_mark.args and mark.kwargs == func_mark.kwargs
-
-
-def transfer_markers(funcobj, cls, mod):
-    """
-    this function transfers class level markers and module level markers
-    into function level markinfo objects
-
-    this is the main reason why marks are so broken
-    the resolution will involve phasing out function level MarkInfo objects
-
-    """
-    for obj in (cls, mod):
-        for mark in get_unpacked_marks(obj):
-            if not _marked(funcobj, mark):
-                store_legacy_markinfo(funcobj, mark)
--- a/testing/web-platform/tests/tools/third_party/pytest/appveyor.yml
+++ b/testing/web-platform/tests/tools/third_party/pytest/appveyor.yml
@@ -37,8 +37,12 @@ install:
   - if "%TOXENV%" == "pypy" call scripts\install-pypy.bat
 
   - C:\Python36\python -m pip install --upgrade --pre tox
 
 build: false  # Not a C# project, build stuff at the test step instead.
 
 test_script:
   - call scripts\call-tox.bat
+
+cache:
+  - '%LOCALAPPDATA%\pip\cache'
+  - '%USERPROFILE%\.cache\pre-commit'
--- a/testing/web-platform/tests/tools/third_party/pytest/bench/bench.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/bench/bench.py
@@ -1,12 +1,13 @@
 import sys
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     import cProfile
-    import pytest
+    import pytest  # NOQA
     import pstats
+
     script = sys.argv[1:] if len(sys.argv) > 1 else "empty.py"
-    stats = cProfile.run('pytest.cmdline.main(%r)' % script, 'prof')
+    stats = cProfile.run("pytest.cmdline.main(%r)" % script, "prof")
     p = pstats.Stats("prof")
     p.strip_dirs()
-    p.sort_stats('cumulative')
+    p.sort_stats("cumulative")
     print(p.print_stats(500))
--- a/testing/web-platform/tests/tools/third_party/pytest/bench/bench_argcomplete.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/bench/bench_argcomplete.py
@@ -1,19 +1,22 @@
 
 
 # 10000 iterations, just for relative comparison
 #                      2.7.5     3.3.2
 # FilesCompleter       75.1109   69.2116
 # FastFilesCompleter    0.7383    1.0760
 
+import timeit
 
-if __name__ == '__main__':
-    import sys
-    import timeit
-    from argcomplete.completers import FilesCompleter
-    from _pytest._argcomplete import FastFilesCompleter
-    count = 1000 # only a few seconds
-    setup = 'from __main__ import FastFilesCompleter\nfc = FastFilesCompleter()'
-    run = 'fc("/d")'
-    sys.stdout.write('%s\n' % (timeit.timeit(run,
-                                setup=setup.replace('Fast', ''), number=count)))
-    sys.stdout.write('%s\n' % (timeit.timeit(run, setup=setup, number=count)))
+imports = [
+    "from argcomplete.completers import FilesCompleter as completer",
+    "from _pytest._argcomplete import FastFilesCompleter as completer",
+]
+
+count = 1000  # only a few seconds
+setup = "%s\nfc = completer()"
+run = 'fc("/d")'
+
+
+if __name__ == "__main__":
+    print(timeit.timeit(run, setup=setup % imports[0], number=count))
+    print((timeit.timeit(run, setup=setup % imports[1], number=count)))
--- a/testing/web-platform/tests/tools/third_party/pytest/bench/empty.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/bench/empty.py
@@ -1,3 +1,4 @@
 import py
+
 for i in range(1000):
     py.builtin.exec_("def test_func_%d(): pass" % i)
--- a/testing/web-platform/tests/tools/third_party/pytest/bench/manyparam.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/bench/manyparam.py
@@ -1,12 +1,15 @@
 
 import pytest
 
-@pytest.fixture(scope='module', params=range(966))
+
+@pytest.fixture(scope="module", params=range(966))
 def foo(request):
     return request.param
 
+
 def test_it(foo):
     pass
+
+
 def test_it2(foo):
     pass
-
--- a/testing/web-platform/tests/tools/third_party/pytest/bench/skip.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/bench/skip.py
@@ -1,10 +1,11 @@
-
+from six.moves import range
 import pytest
 
 
 SKIP = True
 
-@pytest.mark.parametrize("x", xrange(5000))
+
+@pytest.mark.parametrize("x", range(5000))
 def test_foo(x):
     if SKIP:
         pytest.skip("heh")
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/changelog/2920.bugfix
+++ /dev/null
@@ -1,1 +0,0 @@
-Fix issue about ``-p no:<plugin>`` having no effect.
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/changelog/2949.trivial
+++ /dev/null
@@ -1,1 +0,0 @@
-Update github "bugs" link in CONTRIBUTING.rst
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/changelog/2956.bugfix
+++ /dev/null
@@ -1,1 +0,0 @@
-Fix regression with warnings that contained non-strings in their arguments in Python 2.
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/changelog/2957.bugfix
+++ /dev/null
@@ -1,1 +0,0 @@
-Always escape null bytes when setting ``PYTEST_CURRENT_TEST``.
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/changelog/2963.doc
+++ /dev/null
@@ -1,1 +0,0 @@
-Fix broken link to plugin pytest-localserver.
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/changelog/2971.bugfix
+++ /dev/null
@@ -1,1 +0,0 @@
-Fix ``ZeroDivisionError`` when using the ``testmon`` plugin when no tests were actually collected.
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/changelog/2984.bugfix
+++ /dev/null
@@ -1,1 +0,0 @@
-Bring back ``TerminalReporter.writer`` as an alias to ``TerminalReporter._tw``. This alias was removed by accident in the ``3.3.0`` release.
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/changelog/README.rst
@@ -0,0 +1,32 @@
+This directory contains "newsfragments" which are short files that contain a small **ReST**-formatted
+text that will be added to the next ``CHANGELOG``.
+
+The ``CHANGELOG`` will be read by users, so this description should be aimed to pytest users
+instead of describing internal changes which are only relevant to the developers.
+
+Make sure to use full sentences with correct case and punctuation, for example::
+
+    Fix issue with non-ascii messages from the ``warnings`` module.
+
+Each file should be named like ``<ISSUE>.<TYPE>.rst``, where
+``<ISSUE>`` is an issue number, and ``<TYPE>`` is one of:
+
+* ``feature``: new user facing features, like new command-line options and new behavior.
+* ``bugfix``: fixes a reported bug.
+* ``doc``: documentation improvement, like rewording an entire session or adding missing docs.
+* ``removal``: feature deprecation or removal.
+* ``vendor``: changes in packages vendored in pytest.
+* ``trivial``: fixing a small typo or internal change that might be noteworthy.
+
+So for example: ``123.feature.rst``, ``456.bugfix.rst``.
+
+If your PR fixes an issue, use that number here. If there is no issue,
+then after you submit the PR and get the PR number you can add a
+changelog using that instead.
+
+If you are not sure what issue type to use, don't hesitate to ask in your PR.
+
+Note that the ``towncrier`` tool will automatically
+reflow your text, so it will work best if you stick to a single paragraph, but multiple sentences and links are OK
+and encouraged. You can install ``towncrier`` and then run ``towncrier --draft``
+if you want to get a preview of how your change will look in the final release notes.
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/_templates/globaltoc.html
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/_templates/globaltoc.html
@@ -1,19 +1,20 @@
 <h3><a href="{{ pathto(master_doc) }}">{{ _('Table Of Contents') }}</a></h3>
 
 <ul>
   <li><a href="{{ pathto('index') }}">Home</a></li>
+  <li><a href="{{ pathto('getting-started') }}">Install</a></li>
   <li><a href="{{ pathto('contents') }}">Contents</a></li>
-  <li><a href="{{ pathto('getting-started') }}">Install</a></li>
+  <li><a href="{{ pathto('reference') }}">Reference</a></li>
   <li><a href="{{ pathto('example/index') }}">Examples</a></li>
   <li><a href="{{ pathto('customize') }}">Customize</a></li>
-  <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('contributing') }}">Contributing</a></li>
   <li><a href="{{ pathto('backwards-compatibility') }}">Backwards Compatibility</a></li>
   <li><a href="{{ pathto('license') }}">License</a></li>
+  <li><a href="{{ pathto('contact') }}">Contact Channels</a></li>
 </ul>
 
 {%- if display_toc %}
   <hr>
   {{ toc }}
 {%- endif %}
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/_templates/links.html
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/_templates/links.html
@@ -1,11 +1,8 @@
 <h3>Useful Links</h3>
 <ul>
-  <li><a href="{{ pathto('index') }}">The pytest Website</a></li>
-  <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://pypi.org/project/pytest/">pytest @ PyPI</a></li>
   <li><a href="https://github.com/pytest-dev/pytest/">pytest @ GitHub</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="https://media.readthedocs.org/pdf/pytest/latest/pytest.pdf">PDF Documentation</a>
 </ul>
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/_themes/flask/theme.conf
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/_themes/flask/theme.conf
@@ -1,9 +1,9 @@
 [theme]
 inherit = basic
 stylesheet = flasky.css
 pygments_style = flask_theme_support.FlaskyStyle
 
 [options]
 index_logo = ''
 index_logo_height = 120px
-touch_icon = 
+touch_icon =
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/_themes/flask_theme_support.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/_themes/flask_theme_support.py
@@ -1,86 +1,89 @@
 # flasky extensions.  flasky pygments style based on tango style
 from pygments.style import Style
-from pygments.token import Keyword, Name, Comment, String, Error, \
-     Number, Operator, Generic, Whitespace, Punctuation, Other, Literal
+from pygments.token import (
+    Keyword,
+    Name,
+    Comment,
+    String,
+    Error,
+    Number,
+    Operator,
+    Generic,
+    Whitespace,
+    Punctuation,
+    Other,
+    Literal,
+)
 
 
 class FlaskyStyle(Style):
     background_color = "#f8f8f8"
     default_style = ""
 
     styles = {
         # No corresponding class for the following:
-        #Text:                     "", # class:  ''
-        Whitespace:                "underline #f8f8f8",      # class: 'w'
-        Error:                     "#a40000 border:#ef2929", # class: 'err'
-        Other:                     "#000000",                # class 'x'
-
-        Comment:                   "italic #8f5902", # class: 'c'
-        Comment.Preproc:           "noitalic",       # class: 'cp'
-
-        Keyword:                   "bold #004461",   # class: 'k'
-        Keyword.Constant:          "bold #004461",   # class: 'kc'
-        Keyword.Declaration:       "bold #004461",   # class: 'kd'
-        Keyword.Namespace:         "bold #004461",   # class: 'kn'
-        Keyword.Pseudo:            "bold #004461",   # class: 'kp'
-        Keyword.Reserved:          "bold #004461",   # class: 'kr'
-        Keyword.Type:              "bold #004461",   # class: 'kt'
-
-        Operator:                  "#582800",   # class: 'o'
-        Operator.Word:             "bold #004461",   # class: 'ow' - like keywords
-
-        Punctuation:               "bold #000000",   # class: 'p'
-
+        # Text:                     "", # class:  ''
+        Whitespace: "underline #f8f8f8",  # class: 'w'
+        Error: "#a40000 border:#ef2929",  # class: 'err'
+        Other: "#000000",  # class 'x'
+        Comment: "italic #8f5902",  # class: 'c'
+        Comment.Preproc: "noitalic",  # class: 'cp'
+        Keyword: "bold #004461",  # class: 'k'
+        Keyword.Constant: "bold #004461",  # class: 'kc'
+        Keyword.Declaration: "bold #004461",  # class: 'kd'
+        Keyword.Namespace: "bold #004461",  # class: 'kn'
+        Keyword.Pseudo: "bold #004461",  # class: 'kp'
+        Keyword.Reserved: "bold #004461",  # class: 'kr'
+        Keyword.Type: "bold #004461",  # class: 'kt'
+        Operator: "#582800",  # class: 'o'
+        Operator.Word: "bold #004461",  # class: 'ow' - like keywords
+        Punctuation: "bold #000000",  # class: 'p'
         # because special names such as Name.Class, Name.Function, etc.
         # are not recognized as such later in the parsing, we choose them
         # to look the same as ordinary variables.
-        Name:                      "#000000",        # class: 'n'
-        Name.Attribute:            "#c4a000",        # class: 'na' - to be revised
-        Name.Builtin:              "#004461",        # class: 'nb'
-        Name.Builtin.Pseudo:       "#3465a4",        # class: 'bp'
-        Name.Class:                "#000000",        # class: 'nc' - to be revised
-        Name.Constant:             "#000000",        # class: 'no' - to be revised
-        Name.Decorator:            "#888",           # class: 'nd' - to be revised
-        Name.Entity:               "#ce5c00",        # class: 'ni'
-        Name.Exception:            "bold #cc0000",   # class: 'ne'
-        Name.Function:             "#000000",        # class: 'nf'
-        Name.Property:             "#000000",        # class: 'py'
-        Name.Label:                "#f57900",        # class: 'nl'
-        Name.Namespace:            "#000000",        # class: 'nn' - to be revised
-        Name.Other:                "#000000",        # class: 'nx'
-        Name.Tag:                  "bold #004461",   # class: 'nt' - like a keyword
-        Name.Variable:             "#000000",        # class: 'nv' - to be revised
-        Name.Variable.Class:       "#000000",        # class: 'vc' - to be revised
-        Name.Variable.Global:      "#000000",        # class: 'vg' - to be revised
-        Name.Variable.Instance:    "#000000",        # class: 'vi' - to be revised
-
-        Number:                    "#990000",        # class: 'm'
-
-        Literal:                   "#000000",        # class: 'l'
-        Literal.Date:              "#000000",        # class: 'ld'
-
-        String:                    "#4e9a06",        # class: 's'
-        String.Backtick:           "#4e9a06",        # class: 'sb'
-        String.Char:               "#4e9a06",        # class: 'sc'
-        String.Doc:                "italic #8f5902", # class: 'sd' - like a comment
-        String.Double:             "#4e9a06",        # class: 's2'
-        String.Escape:             "#4e9a06",        # class: 'se'
-        String.Heredoc:            "#4e9a06",        # class: 'sh'
-        String.Interpol:           "#4e9a06",        # class: 'si'
-        String.Other:              "#4e9a06",        # class: 'sx'
-        String.Regex:              "#4e9a06",        # class: 'sr'
-        String.Single:             "#4e9a06",        # class: 's1'
-        String.Symbol:             "#4e9a06",        # class: 'ss'
-
-        Generic:                   "#000000",        # class: 'g'
-        Generic.Deleted:           "#a40000",        # class: 'gd'
-        Generic.Emph:              "italic #000000", # class: 'ge'
-        Generic.Error:             "#ef2929",        # class: 'gr'
-        Generic.Heading:           "bold #000080",   # class: 'gh'
-        Generic.Inserted:          "#00A000",        # class: 'gi'
-        Generic.Output:            "#888",           # class: 'go'
-        Generic.Prompt:            "#745334",        # class: 'gp'
-        Generic.Strong:            "bold #000000",   # class: 'gs'
-        Generic.Subheading:        "bold #800080",   # class: 'gu'
-        Generic.Traceback:         "bold #a40000",   # class: 'gt'
+        Name: "#000000",  # class: 'n'
+        Name.Attribute: "#c4a000",  # class: 'na' - to be revised
+        Name.Builtin: "#004461",  # class: 'nb'
+        Name.Builtin.Pseudo: "#3465a4",  # class: 'bp'
+        Name.Class: "#000000",  # class: 'nc' - to be revised
+        Name.Constant: "#000000",  # class: 'no' - to be revised
+        Name.Decorator: "#888",  # class: 'nd' - to be revised
+        Name.Entity: "#ce5c00",  # class: 'ni'
+        Name.Exception: "bold #cc0000",  # class: 'ne'
+        Name.Function: "#000000",  # class: 'nf'
+        Name.Property: "#000000",  # class: 'py'
+        Name.Label: "#f57900",  # class: 'nl'
+        Name.Namespace: "#000000",  # class: 'nn' - to be revised
+        Name.Other: "#000000",  # class: 'nx'
+        Name.Tag: "bold #004461",  # class: 'nt' - like a keyword
+        Name.Variable: "#000000",  # class: 'nv' - to be revised
+        Name.Variable.Class: "#000000",  # class: 'vc' - to be revised
+        Name.Variable.Global: "#000000",  # class: 'vg' - to be revised
+        Name.Variable.Instance: "#000000",  # class: 'vi' - to be revised
+        Number: "#990000",  # class: 'm'
+        Literal: "#000000",  # class: 'l'
+        Literal.Date: "#000000",  # class: 'ld'
+        String: "#4e9a06",  # class: 's'
+        String.Backtick: "#4e9a06",  # class: 'sb'
+        String.Char: "#4e9a06",  # class: 'sc'
+        String.Doc: "italic #8f5902",  # class: 'sd' - like a comment
+        String.Double: "#4e9a06",  # class: 's2'
+        String.Escape: "#4e9a06",  # class: 'se'
+        String.Heredoc: "#4e9a06",  # class: 'sh'
+        String.Interpol: "#4e9a06",  # class: 'si'
+        String.Other: "#4e9a06",  # class: 'sx'
+        String.Regex: "#4e9a06",  # class: 'sr'
+        String.Single: "#4e9a06",  # class: 's1'
+        String.Symbol: "#4e9a06",  # class: 'ss'
+        Generic: "#000000",  # class: 'g'
+        Generic.Deleted: "#a40000",  # class: 'gd'
+        Generic.Emph: "italic #000000",  # class: 'ge'
+        Generic.Error: "#ef2929",  # class: 'gr'
+        Generic.Heading: "bold #000080",  # class: 'gh'
+        Generic.Inserted: "#00A000",  # class: 'gi'
+        Generic.Output: "#888",  # class: 'go'
+        Generic.Prompt: "#745334",  # class: 'gp'
+        Generic.Strong: "bold #000000",  # class: 'gs'
+        Generic.Subheading: "bold #800080",  # class: 'gu'
+        Generic.Traceback: "bold #a40000",  # class: 'gt'
     }
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/index.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/index.rst
@@ -1,16 +1,26 @@
 
 Release announcements
 ===========================================
 
 .. toctree::
    :maxdepth: 2
 
-   
+
+   release-3.6.2
+   release-3.6.1
+   release-3.6.0
+   release-3.5.1
+   release-3.5.0
+   release-3.4.2
+   release-3.4.1
+   release-3.4.0
+   release-3.3.2
+   release-3.3.1
    release-3.3.0
    release-3.2.5
    release-3.2.4
    release-3.2.3
    release-3.2.2
    release-3.2.1
    release-3.2.0
    release-3.1.3
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.0.3.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.0.3.rst
@@ -1,9 +1,9 @@
-py.test 2.0.3: bug fixes and speed ups 
+py.test 2.0.3: bug fixes and speed ups
 ===========================================================================
 
 Welcome to pytest-2.0.3, a maintenance and bug fix release of pytest,
 a mature testing tool for Python, supporting CPython 2.4-3.2, Jython
 and latest PyPy interpreters.  See the extensive docs with tested examples here:
 
     http://pytest.org/
 
@@ -32,9 +32,8 @@ Changes between 2.0.2 and 2.0.3
 
 - don't require zlib (and other libs) for genscript plugin without
   --genscript actually being used.
 
 - speed up skips (by not doing a full traceback representation
   internally)
 
 - fix issue37: avoid invalid characters in junitxml's output
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.1.1.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.1.1.rst
@@ -29,9 +29,8 @@ Changes between 2.1.0 and 2.1.1
 - fix issue60 / fix error conditions involving the creation of __pycache__
 - fix issue63 / assertion rewriting on inserts involving strings containing '%'
 - fix assertion rewriting on calls with a ** arg
 - don't cache rewritten modules if bytecode generation is disabled
 - fix assertion rewriting in read-only directories
 - fix issue59: provide system-out/err tags for junitxml output
 - fix issue61: assertion rewriting on boolean operations with 3 or more operands
 - you can now build a man page with "cd doc ; make man"
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.1.2.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.1.2.rst
@@ -25,9 +25,8 @@ Changes between 2.1.1 and 2.1.2
 ----------------------------------------
 
 - fix assertion rewriting on files with windows newlines on some Python versions
 - refine test discovery by package/module name (--pyargs), thanks Florian Mayer
 - fix issue69 / assertion rewriting fixed on some boolean operations
 - fix issue68 / packages now work with assertion rewriting
 - fix issue66: use different assertion rewriting caches when the -O option is passed
 - don't try assertion rewriting on Jython, use reinterp
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.1.3.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.1.3.rst
@@ -4,17 +4,17 @@ py.test 2.1.3: just some more fixes
 pytest-2.1.3 is a minor backward compatible maintenance release of the
 popular py.test testing tool.  It is commonly used for unit, functional-
 and integration testing.  See extensive docs with examples here:
 
      http://pytest.org/
 
 The release contains another fix to the perfected assertions introduced
 with the 2.1 series as well as the new possibility to customize reporting
-for assertion expressions on a per-directory level.  
+for assertion expressions on a per-directory level.
 
 If you want to install or upgrade pytest, just type one of::
 
     pip install -U pytest # or
     easy_install -U pytest
 
 Thanks to the bug reporters and to Ronny Pfannschmidt, Benjamin Peterson
 and Floris Bruynooghe who implemented the fixes.
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.2.1.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.2.1.rst
@@ -22,20 +22,20 @@ Gospodnetic and Ralf Schmitt.
 best,
 holger krekel
 
 
 Changes between 2.2.0 and 2.2.1
 ----------------------------------------
 
 - fix issue99 (in pytest and py) internallerrors with resultlog now
-  produce better output - fixed by normalizing pytest_internalerror 
+  produce better output - fixed by normalizing pytest_internalerror
   input arguments.
 - fix issue97 / traceback issues (in pytest and py) improve traceback output
   in conjunction with jinja2 and cython which hack tracebacks
 - fix issue93 (in pytest and pytest-xdist) avoid "delayed teardowns":
   the final test in a test node will now run its teardown directly
   instead of waiting for the end of the session. Thanks Dave Hunt for
   the good reporting and feedback.  The pytest_runtest_protocol as well
-  as the pytest_runtest_teardown hooks now have "nextitem" available 
+  as the pytest_runtest_teardown hooks now have "nextitem" available
   which will be None indicating the end of the test run.
 - fix collection crash due to unknown-source collected items, thanks
   to Ralf Schmitt (fixed by depending on a more recent pylib)
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.2.2.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.2.2.rst
@@ -1,15 +1,15 @@
 pytest-2.2.2: bug fixes
 ===========================================================================
 
 pytest-2.2.2 (updated to 2.2.3 to fix packaging issues) is a minor
 backward-compatible release of the versatile py.test testing tool.   It
 contains bug fixes and a few refinements particularly to reporting with
-"--collectonly", see below for betails.  
+"--collectonly", see below for betails.
 
 For general information see here:
 
      http://pytest.org/
 
 To install or upgrade pytest:
 
     pip install -U pytest # or
@@ -22,22 +22,22 @@ best,
 holger krekel
 
 
 Changes between 2.2.1 and 2.2.2
 ----------------------------------------
 
 - fix issue101: wrong args to unittest.TestCase test function now
   produce better output
-- fix issue102: report more useful errors and hints for when a 
+- fix issue102: report more useful errors and hints for when a
   test directory was renamed and some pyc/__pycache__ remain
 - fix issue106: allow parametrize to be applied multiple times
   e.g. from module, class and at function level.
 - fix issue107: actually perform session scope finalization
 - don't check in parametrize if indirect parameters are funcarg names
 - add chdir method to monkeypatch funcarg
 - fix crash resulting from calling monkeypatch undo a second time
 - fix issue115: make --collectonly robust against early failure
   (missing files/directories)
 - "-qq --collectonly" now shows only files and the number of tests in them
-- "-q --collectonly" now shows test ids 
+- "-q --collectonly" now shows test ids
 - allow adding of attributes to test reports such that it also works
   with distributed testing (no upgrade of pytest-xdist needed)
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.2.4.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.2.4.rst
@@ -31,9 +31,8 @@ Changes between 2.2.3 and 2.2.4
 - document integration with the extended distribute/setuptools test commands
 - fix issue 140: properly get the real functions
   of bound classmethods for setup/teardown_class
 - fix issue #141: switch from the deceased paste.pocoo.org to bpaste.net
 - fix issue #143: call unconfigure/sessionfinish always when
   configure/sessionstart where called
 - fix issue #144: better mangle test ids to junitxml classnames
 - upgrade distribute_setup.py to 0.6.27
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.0.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.0.rst
@@ -1,20 +1,20 @@
 pytest-2.3: improved fixtures / better unittest integration
 =============================================================================
 
-pytest-2.3 comes with many major improvements for fixture/funcarg management 
+pytest-2.3 comes with many major improvements for fixture/funcarg management
 and parametrized testing in Python.  It is now easier, more efficient and
 more predicatable to re-run the same tests with different fixture
 instances.  Also, you can directly declare the caching "scope" of
 fixtures so that dependent tests throughout your whole test suite can
 re-use database or other expensive fixture objects with ease.  Lastly,
 it's possible for fixture functions (formerly known as funcarg
 factories) to use other fixtures, allowing for a completely modular and
-re-useable fixture design. 
+re-useable fixture design.
 
 For detailed info and tutorial-style examples, see:
 
     http://pytest.org/latest/fixture.html
 
 Moreover, there is now support for using pytest fixtures/funcargs with
 unittest-style suites, see here for examples:
 
@@ -22,33 +22,33 @@ unittest-style suites, see here for exam
 
 Besides, more unittest-test suites are now expected to "simply work"
 with pytest.
 
 All changes are backward compatible and you should be able to continue
 to run your test suites and 3rd party plugins that worked with
 pytest-2.2.4.
 
-If you are interested in the precise reasoning (including examples) of the 
+If you are interested in the precise reasoning (including examples) of the
 pytest-2.3 fixture evolution, please consult
 http://pytest.org/latest/funcarg_compare.html
 
 For general info on installation and getting started:
 
     http://pytest.org/latest/getting-started.html
 
 Docs and PDF access as usual at:
 
     http://pytest.org
 
 and more details for those already in the knowing of pytest can be found
 in the CHANGELOG below.
 
 Particular thanks for this release go to Floris Bruynooghe, Alex Okrushko
-Carl Meyer, Ronny Pfannschmidt, Benjamin Peterson and Alex Gaynor for helping 
+Carl Meyer, Ronny Pfannschmidt, Benjamin Peterson and Alex Gaynor for helping
 to get the new features right and well integrated.  Ronny and Floris
 also helped to fix a number of bugs and yet more people helped by
 providing bug reports.
 
 have fun,
 holger krekel
 
 
@@ -89,17 +89,17 @@ Changes between 2.2.4 and 2.3.0
 
 - fix issue128: show captured output when capsys/capfd are used
 
 - fix issue179: properly show the dependency chain of factories
 
 - pluginmanager.register(...) now raises ValueError if the
   plugin has been already registered or the name is taken
 
-- fix issue159: improve http://pytest.org/latest/faq.html 
+- fix issue159: improve http://pytest.org/latest/faq.html
   especially with respect to the "magic" history, also mention
   pytest-django, trial and unittest integration.
 
 - make request.keywords and node.keywords writable.  All descendant
   collection nodes will see keyword values.  Keywords are dictionaries
   containing markers and other info.
 
 - fix issue 178: xml binary escapes are now wrapped in py.xml.raw
@@ -120,15 +120,14 @@ Changes between 2.2.4 and 2.3.0
 - fix issue 156: monkeypatch correctly handles class level descriptors
 
 - reporting refinements:
 
   - pytest_report_header now receives a "startdir" so that
     you can use startdir.bestrelpath(yourpath) to show
     nice relative path
 
-  - allow plugins to implement both pytest_report_header and 
+  - allow plugins to implement both pytest_report_header and
     pytest_sessionstart (sessionstart is invoked first).
 
   - don't show deselected reason line if there is none
 
   - py.test -vv will show all of assert comparisons instead of truncating
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.1.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.1.rst
@@ -1,23 +1,23 @@
 pytest-2.3.1: fix regression with factory functions
 ===========================================================================
 
 pytest-2.3.1 is a quick follow-up release:
 
-- fix issue202 - regression with fixture functions/funcarg factories:  
-  using "self" is now safe again and works as in 2.2.4.  Thanks 
+- fix issue202 - regression with fixture functions/funcarg factories:
+  using "self" is now safe again and works as in 2.2.4.  Thanks
   to Eduard Schettino for the quick bug report.
 
-- disable pexpect pytest self tests on Freebsd - thanks Koob for the 
+- disable pexpect pytest self tests on Freebsd - thanks Koob for the
   quick reporting
 
 - fix/improve interactive docs with --markers
 
-See 
+See
 
      http://pytest.org/
 
 for general information.  To install or upgrade pytest:
 
     pip install -U pytest # or
     easy_install -U pytest
 
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.2.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.2.rst
@@ -3,35 +3,35 @@ pytest-2.3.2: some fixes and more traceb
 
 pytest-2.3.2 is another stabilization release:
 
 - issue 205: fixes a regression with conftest detection
 - issue 208/29: fixes traceback-printing speed in some bad cases
 - fix teardown-ordering for parametrized setups
 - fix unittest and trial compat behaviour with respect  to runTest() methods
 - issue 206 and others: some improvements to packaging
-- fix issue127 and others: improve some docs 
+- fix issue127 and others: improve some docs
 
-See 
+See
 
      http://pytest.org/
 
 for general information.  To install or upgrade pytest:
 
     pip install -U pytest # or
     easy_install -U pytest
 
 best,
 holger krekel
 
 
 Changes between 2.3.1 and 2.3.2
 -----------------------------------
 
-- fix issue208 and fix issue29 use new py version to avoid long pauses 
+- fix issue208 and fix issue29 use new py version to avoid long pauses
   when printing tracebacks in long modules
 
 - fix issue205 - conftests in subdirs customizing
   pytest_pycollect_makemodule and pytest_pycollect_makeitem
   now work properly
 
 - fix teardown-ordering for parametrized setups
 
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.3.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.3.rst
@@ -1,27 +1,27 @@
 pytest-2.3.3: integration fixes, py24 support, ``*/**`` shown in traceback
 ===========================================================================
 
 pytest-2.3.3 is another stabilization release of the py.test tool
 which offers uebersimple assertions, scalable fixture mechanisms
 and deep customization for testing with Python.  Particularly,
 this release provides:
 
-- integration fixes and improvements related to flask, numpy, nose, 
+- integration fixes and improvements related to flask, numpy, nose,
   unittest, mock
 
 - makes pytest work on py24 again (yes, people sometimes still need to use it)
 
 - show ``*,**`` args in pytest tracebacks
 
 Thanks to Manuel Jacob, Thomas Waldmann, Ronny Pfannschmidt, Pavel Repin
 and Andreas Taumoefolau for providing patches and all for the issues.
 
-See 
+See
 
      http://pytest.org/
 
 for general information.  To install or upgrade pytest:
 
     pip install -U pytest # or
     easy_install -U pytest
 
@@ -54,9 +54,8 @@ Changes between 2.3.2 and 2.3.3
 - in tracebacks *,** arg values are now shown next to normal arguments
   (thanks Manuel Jacob)
 
 - fix issue217 - support mock.patch with pytest's fixtures - note that
   you need either mock-1.0.1 or the python3.3 builtin unittest.mock.
 
 - fix issue127 - improve documentation for pytest_addoption() and
   add a ``config.getoption(name)`` helper function for consistency.
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.4.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.4.rst
@@ -5,33 +5,33 @@ pytest-2.3.4 is a small stabilization re
 which offers uebersimple assertions, scalable fixture mechanisms
 and deep customization for testing with Python.  This release
 comes with the following fixes and features:
 
 - make "-k" option accept an expressions the same as with "-m" so that one
   can write: -k "name1 or name2" etc.  This is a slight usage incompatibility
   if you used special syntax like "TestClass.test_method" which you now
   need to write as -k "TestClass and test_method" to match a certain
-  method in a certain test class.  
+  method in a certain test class.
 - allow to dynamically define markers via
   item.keywords[...]=assignment integrating with "-m" option
-- yielded test functions will now have autouse-fixtures active but 
+- yielded test functions will now have autouse-fixtures active but
   cannot accept fixtures as funcargs - it's anyway recommended to
   rather use the post-2.0 parametrize features instead of yield, see:
   http://pytest.org/latest/example/parametrize.html
 - fix autouse-issue where autouse-fixtures would not be discovered
-  if defined in a a/conftest.py file and tests in a/tests/test_some.py
+  if defined in an a/conftest.py file and tests in a/tests/test_some.py
 - fix issue226 - LIFO ordering for fixture teardowns
 - fix issue224 - invocations with >256 char arguments now work
 - fix issue91 - add/discuss package/directory level setups in example
 - fixes related to autouse discovery and calling
 
 Thanks in particular to Thomas Waldmann for spotting and reporting issues.
 
-See 
+See
 
      http://pytest.org/
 
 for general information.  To install or upgrade pytest:
 
     pip install -U pytest # or
     easy_install -U pytest
 
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.5.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.3.5.rst
@@ -8,18 +8,18 @@ prior version are expected to work unmod
 few interesting new plugins saw the light last month:
 
 - pytest-instafail: show failure information while tests are running
 - pytest-qt: testing of GUI applications written with QT/Pyside
 - pytest-xprocess: managing external processes across test runs
 - pytest-random: randomize test ordering
 
 And several others like pytest-django saw maintenance releases.
-For a more complete list, check out 
-https://pypi.python.org/pypi?%3Aaction=search&term=pytest&submit=search.
+For a more complete list, check out
+https://pypi.org/search/?q=pytest
 
 For general information see:
 
      http://pytest.org/
 
 To install or upgrade pytest:
 
     pip install -U pytest # or
@@ -76,22 +76,21 @@ Changes between 2.3.4 and 2.3.5
 
 - move long description of distribution into README.rst
 
 - improve docstring for metafunc.parametrize()
 
 - fix bug where using capsys with pytest.set_trace() in a test
   function would break when looking at capsys.readouterr()
 
-- allow to specify prefixes starting with "_" when 
+- allow to specify prefixes starting with "_" when
   customizing python_functions test discovery. (thanks Graham Horler)
 
 - improve PYTEST_DEBUG tracing output by putting
   extra data on a new lines with additional indent
 
 - ensure OutcomeExceptions like skip/fail have initialized exception attributes
 
 - issue 260 - don't use nose special setup on plain unittest cases
 
 - fix issue134 - print the collect errors that prevent running specified test items
 
 - fix issue266 - accept unicode in MarkEvaluator expressions
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.4.0.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.4.0.rst
@@ -1,57 +1,57 @@
 pytest-2.4.0: new fixture features/hooks and bug fixes
 ===========================================================================
 
-The just released pytest-2.4.0 brings many improvements and numerous 
+The just released pytest-2.4.0 brings many improvements and numerous
 bug fixes while remaining plugin- and test-suite compatible apart
-from a few supposedly very minor incompatibilities.  See below for 
+from a few supposedly very minor incompatibilities.  See below for
 a full list of details.  A few feature highlights:
 
 - new yield-style fixtures `pytest.yield_fixture
   <http://pytest.org/latest/yieldfixture.html>`_, allowing to use
   existing with-style context managers in fixture functions.
 
 - improved pdb support: ``import pdb ; pdb.set_trace()`` now works
   without requiring prior disabling of stdout/stderr capturing.
   Also the ``--pdb`` options works now on collection and internal errors
-  and we introduced a new experimental hook for IDEs/plugins to 
+  and we introduced a new experimental hook for IDEs/plugins to
   intercept debugging: ``pytest_exception_interact(node, call, report)``.
 
 - shorter monkeypatch variant to allow specifying an import path as
   a target, for example: ``monkeypatch.setattr("requests.get", myfunc)``
 
 - better unittest/nose compatibility: all teardown methods are now only
   called if the corresponding setup method succeeded.
 
 - integrate tab-completion on command line options if you
-  have `argcomplete <http://pypi.python.org/pypi/argcomplete>`_ 
+  have `argcomplete <http://pypi.python.org/pypi/argcomplete>`_
   configured.
 
 - allow boolean expression directly with skipif/xfail
   if a "reason" is also specified.
 
 - a new hook ``pytest_load_initial_conftests`` allows plugins like
-  `pytest-django <http://pypi.python.org/pypi/pytest-django>`_ to
+  `pytest-django <https://pypi.org/project/pytest-django/>`_ to
   influence the environment before conftest files import ``django``.
 
 - reporting: color the last line red or green depending if
   failures/errors occurred or everything passed.
 
-The documentation has been updated to accommodate the changes, 
-see `http://pytest.org <http://pytest.org>`_ 
+The documentation has been updated to accommodate the changes,
+see `http://pytest.org <http://pytest.org>`_
 
 To install or upgrade pytest::
 
     pip install -U pytest # or
     easy_install -U pytest
 
 
-**Many thanks to all who helped, including Floris Bruynooghe, 
-Brianna Laugher, Andreas Pelme, Anthon van der Neut, Anatoly Bubenkoff, 
+**Many thanks to all who helped, including Floris Bruynooghe,
+Brianna Laugher, Andreas Pelme, Anthon van der Neut, Anatoly Bubenkoff,
 Vladimir Keleshev, Mathieu Agopian, Ronny Pfannschmidt, Christian
 Theunert and many others.**
 
 may passing tests be with you,
 
 holger krekel
 
 Changes between 2.3.5 and 2.4
@@ -96,22 +96,22 @@ new features:
 
 - reporting: color the last line red or green depending if
   failures/errors occurred or everything passed.  thanks Christian
   Theunert.
 
 - make "import pdb ; pdb.set_trace()" work natively wrt capturing (no
   "-s" needed anymore), making ``pytest.set_trace()`` a mere shortcut.
 
-- fix issue181: --pdb now also works on collect errors (and 
-  on internal errors) .  This was implemented by a slight internal 
-  refactoring and the introduction of a new hook 
+- fix issue181: --pdb now also works on collect errors (and
+  on internal errors) .  This was implemented by a slight internal
+  refactoring and the introduction of a new hook
   ``pytest_exception_interact`` hook (see next item).
 
-- fix issue341: introduce new experimental hook for IDEs/terminals to 
+- fix issue341: introduce new experimental hook for IDEs/terminals to
   intercept debugging: ``pytest_exception_interact(node, call, report)``.
 
 - new monkeypatch.setattr() variant to provide a shorter
   invocation for patching out classes/functions from modules:
 
      monkeypatch.setattr("requests.get", myfunc)
 
   will replace the "get" function of the "requests" module with ``myfunc``.
@@ -119,17 +119,17 @@ new features:
 - fix issue322: tearDownClass is not run if setUpClass failed. Thanks
   Mathieu Agopian for the initial fix.  Also make all of pytest/nose
   finalizer mimic the same generic behaviour: if a setupX exists and
   fails, don't run teardownX.  This internally introduces a new method
   "node.addfinalizer()" helper which can only be called during the setup
   phase of a node.
 
 - simplify pytest.mark.parametrize() signature: allow to pass a
-  CSV-separated string to specify argnames.  For example: 
+  CSV-separated string to specify argnames.  For example:
   ``pytest.mark.parametrize("input,expected",  [(1,2), (2,3)])``
   works as well as the previous:
   ``pytest.mark.parametrize(("input", "expected"), ...)``.
 
 - add support for setUpModule/tearDownModule detection, thanks Brian Okken.
 
 - integrate tab-completion on options through use of "argcomplete".
   Thanks Anthon van der Neut for the PR.
@@ -144,20 +144,20 @@ new features:
 - fix issue 308 - allow to mark/xfail/skip individual parameter sets
   when parametrizing.  Thanks Brianna Laugher.
 
 - call new experimental pytest_load_initial_conftests hook to allow
   3rd party plugins to do something before a conftest is loaded.
 
 Bug fixes:
 
-- fix issue358 - capturing options are now parsed more properly 
+- fix issue358 - capturing options are now parsed more properly
   by using a new parser.parse_known_args method.
 
-- pytest now uses argparse instead of optparse (thanks Anthon) which 
+- pytest now uses argparse instead of optparse (thanks Anthon) which
   means that "argparse" is added as a dependency if installing into python2.6
   environments or below.
 
 - fix issue333: fix a case of bad unittest/pytest hook interaction.
 
 - PR27: correctly handle nose.SkipTest during collection.  Thanks
   Antonio Cuni, Ronny Pfannschmidt.
 
@@ -188,38 +188,37 @@ Bug fixes:
   reporting (thanks Katarzyna Jachim)
 
 - fix issue300 - Fix order of conftest loading when starting py.test
   in a subdirectory.
 
 - fix issue323 - sorting of many module-scoped arg parametrizations
 
 - make sessionfinish hooks execute with the same cwd-context as at
-  session start (helps fix plugin behaviour which write output files 
+  session start (helps fix plugin behaviour which write output files
   with relative path such as pytest-cov)
 
 - fix issue316 - properly reference collection hooks in docs
 
 - fix issue 306 - cleanup of -k/-m options to only match markers/test
   names/keywords respectively.  Thanks Wouter van Ackooy.
 
-- improved doctest counting for doctests in python modules -- 
+- improved doctest counting for doctests in python modules --
   files without any doctest items will not show up anymore
   and doctest examples are counted as separate test items.
   thanks Danilo Bellini.
 
 - fix issue245 by depending on the released py-1.4.14
   which fixes py.io.dupfile to work with files with no
   mode. Thanks Jason R. Coombs.
 
 - fix junitxml generation when test output contains control characters,
-  addressing issue267, thanks Jaap Broekhuizen 
+  addressing issue267, thanks Jaap Broekhuizen
 
 - fix issue338: honor --tb style for setup/teardown errors as well.  Thanks Maho.
 
 - fix issue307 - use yaml.safe_load in example, thanks Mark Eichin.
 
 - better parametrize error messages, thanks Brianna Laugher
 
 - pytest_terminal_summary(terminalreporter) hooks can now use
-  ".section(title)" and ".line(msg)" methods to print extra 
+  ".section(title)" and ".line(msg)" methods to print extra
   information at the end of a test run.
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.4.1.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.4.1.rst
@@ -3,17 +3,17 @@ pytest-2.4.1: fixing three regressions c
 
 pytest-2.4.1 is a quick follow up release to fix three regressions
 compared to 2.3.5 before they hit more people:
 
 - When using parser.addoption() unicode arguments to the
   "type" keyword should also be converted to the respective types.
   thanks Floris Bruynooghe, @dnozay. (fixes issue360 and issue362)
 
-- fix dotted filename completion when using argcomplete 
+- fix dotted filename completion when using argcomplete
   thanks Anthon van der Neuth. (fixes issue361)
 
 - fix regression when a 1-tuple ("arg",) is used for specifying
   parametrization (the values of the parametrization were passed
   nested in a tuple).  Thanks Donald Stufft.
 
 - also merge doc typo fixes, thanks Andy Dirnberger
 
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.4.2.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.4.2.rst
@@ -21,19 +21,19 @@ pytest-2.4.2 is another bug-fixing relea
 
 - introduce node.get_marker/node.add_marker API for plugins
   like pytest-pep8 and pytest-flakes to avoid the messy
   details of the node.keywords  pseudo-dicts.  Adapted
   docs.
 
 - remove attempt to "dup" stdout at startup as it's icky.
   the normal capturing should catch enough possibilities
-  of tests messing up standard FDs. 
+  of tests messing up standard FDs.
 
-- add pluginmanager.do_configure(config) as a link to 
+- add pluginmanager.do_configure(config) as a link to
   config.do_configure() for plugin-compatibility
 
 as usual, docs at http://pytest.org and upgrades via::
 
     pip install -U pytest
 
 have fun,
 holger krekel
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.5.0.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.5.0.rst
@@ -1,33 +1,33 @@
 pytest-2.5.0: now down to ZERO reported bugs!
 ===========================================================================
 
 pytest-2.5.0 is a big fixing release, the result of two community bug
 fixing days plus numerous additional works from many people and
 reporters.  The release should be fully compatible to 2.4.2, existing
-plugins and test suites.  We aim at maintaining this level of ZERO reported 
+plugins and test suites.  We aim at maintaining this level of ZERO reported
 bugs because it's no fun if your testing tool has bugs, is it?  Under a
 condition, though: when submitting a bug report please provide
 clear information about the circumstances and a simple example which
 reproduces the problem.
 
 The issue tracker is of course not empty now.  We have many remaining
 "enhacement" issues which we'll hopefully can tackle in 2014 with your
 help.
 
 For those who use older Python versions, please note that pytest is not
 automatically tested on python2.5 due to virtualenv, setuptools and tox
 not supporting it anymore.  Manual verification shows that it mostly
-works fine but it's not going to be part of the automated release 
+works fine but it's not going to be part of the automated release
 process and thus likely to break in the future.
 
-As usual, current docs are at 
+As usual, current docs are at
 
-    http://pytest.org 
+    http://pytest.org
 
 and you can upgrade from pypi via::
 
     pip install -U pytest
 
 Particular thanks for helping with this release go to Anatoly Bubenkoff,
 Floris Bruynooghe, Marc Abramowitz, Ralph Schmitt, Ronny Pfannschmidt,
 Donald Stufft, James Lan, Rob Dennis, Jason R. Coombs, Mathieu Agopian,
@@ -35,58 +35,58 @@ Virgil Dupras, Bruno Oliveira, Alex Gayn
 
 have fun,
 holger krekel
 
 
 2.5.0
 -----------------------------------
 
-- dropped python2.5 from automated release testing of pytest itself 
-  which means it's probably going to break soon (but still works 
+- dropped python2.5 from automated release testing of pytest itself
+  which means it's probably going to break soon (but still works
   with this release we believe).
 
 - simplified and fixed implementation for calling finalizers when
-  parametrized fixtures or function arguments are involved.  finalization 
+  parametrized fixtures or function arguments are involved.  finalization
   is now performed lazily at setup time instead of in the "teardown phase".
-  While this might sound odd at first, it helps to ensure that we are 
+  While this might sound odd at first, it helps to ensure that we are
   correctly handling setup/teardown even in complex code.  User-level code
   should not be affected unless it's implementing the pytest_runtest_teardown
   hook and expecting certain fixture instances are torn down within (very
   unlikely and would have been unreliable anyway).
 
-- PR90: add --color=yes|no|auto option to force terminal coloring 
+- PR90: add --color=yes|no|auto option to force terminal coloring
   mode ("auto" is default).  Thanks Marc Abramowitz.
 
 - fix issue319 - correctly show unicode in assertion errors.  Many
   thanks to Floris Bruynooghe for the complete PR.  Also means
   we depend on py>=1.4.19 now.
 
-- fix issue396 - correctly sort and finalize class-scoped parametrized 
-  tests independently from number of methods on the class.  
+- fix issue396 - correctly sort and finalize class-scoped parametrized
+  tests independently from number of methods on the class.
 
 - refix issue323 in a better way -- parametrization should now never
   cause Runtime Recursion errors because the underlying algorithm
   for re-ordering tests per-scope/per-fixture is not recursive
   anymore (it was tail-call recursive before which could lead
   to problems for more than >966 non-function scoped parameters).
 
 - fix issue290 - there is preliminary support now for parametrizing
-  with repeated same values (sometimes useful to test if calling 
+  with repeated same values (sometimes useful to test if calling
   a second time works as with the first time).
 
 - close issue240 - document precisely how pytest module importing
-  works, discuss the two common test directory layouts, and how it 
+  works, discuss the two common test directory layouts, and how it
   interacts with PEP420-namespace packages.
 
 - fix issue246 fix finalizer order to be LIFO on independent fixtures
-  depending on a parametrized higher-than-function scoped fixture. 
+  depending on a parametrized higher-than-function scoped fixture.
   (was quite some effort so please bear with the complexity of this sentence :)
   Thanks Ralph Schmitt for the precise failure example.
- 
+
 - fix issue244 by implementing special index for parameters to only use
   indices for paramentrized test ids
 
 - fix issue287 by running all finalizers but saving the exception
   from the first failing finalizer and re-raising it so teardown will
   still have failed.  We reraise the first failing exception because
   it might be the cause for other finalizers to fail.
 
@@ -94,27 +94,27 @@ 2.5.0
   are used with test methods.  This fixues issue346 and should
   help with random "xdist" collection failures.  Thanks to
   Ronny Pfannschmidt and Donald Stufft for helping to isolate it.
 
 - fix issue357 - special case "-k" expressions to allow for
   filtering with simple strings that are not valid python expressions.
   Examples: "-k 1.3" matches all tests parametrized with 1.3.
   "-k None" filters all tests that have "None" in their name
-  and conversely "-k 'not None'". 
+  and conversely "-k 'not None'".
   Previously these examples would raise syntax errors.
-  
+
 - fix issue384 by removing the trial support code
   since the unittest compat enhancements allow
   trial to handle it on its own
 
 - don't hide an ImportError when importing a plugin produces one.
   fixes issue375.
 
-- fix issue275 - allow usefixtures and autouse fixtures 
+- fix issue275 - allow usefixtures and autouse fixtures
   for running doctest text files.
 
 - fix issue380 by making --resultlog only rely on longrepr instead
   of the "reprcrash" attribute which only exists sometimes.
 
 - address issue122: allow @pytest.fixture(params=iterator) by exploding
   into a list early on.
 
@@ -130,46 +130,45 @@ 2.5.0
 
 - In assertion rewriting mode on Python 2, fix the detection of coding
   cookies. See issue #330.
 
 - make "--runxfail" turn imperative pytest.xfail calls into no ops
   (it already did neutralize pytest.mark.xfail markers)
 
 - refine pytest / pkg_resources interactions: The AssertionRewritingHook
-  PEP302 compliant loader now registers itself with setuptools/pkg_resources 
+  PEP302 compliant loader now registers itself with setuptools/pkg_resources
   properly so that the pkg_resources.resource_stream method works properly.
   Fixes issue366.  Thanks for the investigations and full PR to Jason R. Coombs.
 
 - pytestconfig fixture is now session-scoped as it is the same object during the
-  whole test run.  Fixes issue370. 
+  whole test run.  Fixes issue370.
 
 - avoid one surprising case of marker malfunction/confusion::
-  
+
       @pytest.mark.some(lambda arg: ...)
       def test_function():
 
-  would not work correctly because pytest assumes @pytest.mark.some 
-  gets a function to be decorated already.  We now at least detect if this 
+  would not work correctly because pytest assumes @pytest.mark.some
+  gets a function to be decorated already.  We now at least detect if this
   arg is a lambda and thus the example will work.  Thanks Alex Gaynor
   for bringing it up.
 
 - xfail a test on pypy that checks wrong encoding/ascii (pypy does
   not error out). fixes issue385.
 
 - internally make varnames() deal with classes's __init__,
   although it's not needed by pytest itself atm.  Also
   fix caching.  Fixes issue376.
 
-- fix issue221 - handle importing of namespace-package with no 
+- fix issue221 - handle importing of namespace-package with no
   __init__.py properly.
 
 - refactor internal FixtureRequest handling to avoid monkeypatching.
-  One of the positive user-facing effects is that the "request" object 
+  One of the positive user-facing effects is that the "request" object
   can now be used in closures.
 
 - fixed version comparison in pytest.importskip(modname, minverstring)
 
 - fix issue377 by clarifying in the nose-compat docs that pytest
   does not duplicate the unittest-API into the "plain" namespace.
 
 - fix verbose reporting for @mock'd test functions
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.5.1.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.5.1.rst
@@ -1,27 +1,27 @@
 pytest-2.5.1: fixes and new home page styling
 ===========================================================================
 
-pytest is a mature Python testing tool with more than a 1000 tests 
-against itself, passing on many different interpreters and platforms.  
+pytest is a mature Python testing tool with more than a 1000 tests
+against itself, passing on many different interpreters and platforms.
 
 The 2.5.1 release maintains the "zero-reported-bugs" promise by fixing
 the three bugs reported since the last release a few days ago.  It also
 features a new home page styling implemented by Tobias Bieniek, based on
 the flask theme from Armin Ronacher:
 
     http://pytest.org
 
-If you have anything more to improve styling and docs, 
+If you have anything more to improve styling and docs,
 we'd be very happy to merge further pull requests.
 
 On the coding side, the release also contains a little enhancement to
 fixture decorators allowing to directly influence generation of test
-ids, thanks to Floris Bruynooghe.  Other thanks for helping with 
+ids, thanks to Floris Bruynooghe.  Other thanks for helping with
 this release go to Anatoly Bubenkoff and Ronny Pfannschmidt.
 
 As usual, you can upgrade from pypi via::
 
     pip install -U pytest
 
 have fun and a nice remaining "bug-free" time of the year :)
 holger krekel
@@ -32,16 +32,15 @@ 2.5.1
 - merge new documentation styling PR from Tobias Bieniek.
 
 - fix issue403: allow parametrize of multiple same-name functions within
   a collection node.  Thanks Andreas Kloeckner and Alex Gaynor for reporting
   and analysis.
 
 - Allow parameterized fixtures to specify the ID of the parameters by
   adding an ids argument to pytest.fixture() and pytest.yield_fixture().
-  Thanks Floris Bruynooghe. 
+  Thanks Floris Bruynooghe.
 
 - fix issue404 by always using the binary xml escape in the junitxml
   plugin.  Thanks Ronny Pfannschmidt.
 
 - fix issue407: fix addoption docstring to point to argparse instead of
   optparse. Thanks Daniel D. Wright.
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.5.2.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.5.2.rst
@@ -1,64 +1,63 @@
-pytest-2.5.2: fixes 
+pytest-2.5.2: fixes
 ===========================================================================
 
-pytest is a mature Python testing tool with more than a 1000 tests 
-against itself, passing on many different interpreters and platforms.  
+pytest is a mature Python testing tool with more than a 1000 tests
+against itself, passing on many different interpreters and platforms.
 
 The 2.5.2 release fixes a few bugs with two maybe-bugs remaining and
 actively being worked on (and waiting for the bug reporter's input).
 We also have a new contribution guide thanks to Piotr Banaszkiewicz
 and others.
 
 See docs at:
 
     http://pytest.org
 
 As usual, you can upgrade from pypi via::
 
     pip install -U pytest
 
 Thanks to the following people who contributed to this release:
 
-    Anatoly Bubenkov 
+    Anatoly Bubenkov
     Ronny Pfannschmidt
     Floris Bruynooghe
-    Bruno Oliveira 
-    Andreas Pelme 
+    Bruno Oliveira
+    Andreas Pelme
     Jurko Gospodnetić
-    Piotr Banaszkiewicz 
-    Simon Liedtke 
-    lakka 
-    Lukasz Balcerzak 
-    Philippe Muller 
-    Daniel Hahler 
+    Piotr Banaszkiewicz
+    Simon Liedtke
+    lakka
+    Lukasz Balcerzak
+    Philippe Muller
+    Daniel Hahler
 
 have fun,
 holger krekel
 
 2.5.2
 -----------------------------------
 
 - fix issue409 -- better interoperate with cx_freeze by not
-  trying to import from collections.abc which causes problems 
+  trying to import from collections.abc which causes problems
   for py27/cx_freeze.  Thanks Wolfgang L. for reporting and tracking it down.
 
 - fixed docs and code to use "pytest" instead of "py.test" almost everywhere.
-  Thanks Jurko Gospodnetic for the complete PR.  
+  Thanks Jurko Gospodnetic for the complete PR.
 
 - fix issue425: mention at end of "py.test -h" that --markers
   and --fixtures work according to specified test path (or current dir)
 
 - fix issue413: exceptions with unicode attributes are now printed
   correctly also on python2 and with pytest-xdist runs. (the fix
   requires py-1.4.20)
 
 - copy, cleanup and integrate py.io capture
   from pylib 1.4.20.dev2 (rev 13d9af95547e)
-  
+
 - address issue416: clarify docs as to conftest.py loading semantics
 
 - fix issue429: comparing byte strings with non-ascii chars in assert
   expressions now work better.  Thanks Floris Bruynooghe.
 
 - make capfd/capsys.capture private, its unused and shouldn't be exposed
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.6.1.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.6.1.rst
@@ -47,13 +47,12 @@ Changes 2.6.1
 
 - fix integration of pytest with unittest.mock.patch decorator when
   it uses the "new" argument.  Thanks Nicolas Delaby for test and PR.
 
 - fix issue with detecting conftest files if the arguments contain
   "::" node id specifications (copy pasted from "-v" output)
 
 - fix issue544 by only removing "@NUM" at the end of "::" separated parts
-  and if the part has an ".py" extension
+  and if the part has a ".py" extension
 
 - don't use py.std import helper, rather import things directly.
   Thanks Bruno Oliveira.
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.6.2.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.6.2.rst
@@ -44,9 +44,8 @@ 2.6.2
 
 - Fix example in monkeypatch documentation, thanks t-8ch.
 
 - fix issue572: correct tmpdir doc example for python3.
 
 - Do not mark as universal wheel because Python 2.6 is different from
   other builds due to the extra argparse dependency.  Fixes issue566.
   Thanks sontek.
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.6.3.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.6.3.rst
@@ -44,9 +44,8 @@ Changes 2.6.3
   CWD outside of a test package pytest would get fixture discovery wrong.
   Thanks to Wolfgang Schnerring for figuring out a reproducible example.
 
 - Introduce pytest_enter_pdb hook (needed e.g. by pytest_timeout to cancel the
   timeout when interactively entering pdb).  Thanks Wolfgang Schnerring.
 
 - check xfail/skip also with non-python function test items. Thanks
   Floris Bruynooghe.
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.7.0.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.7.0.rst
@@ -93,9 +93,8 @@ 2.7.0 (compared to 2.6.4)
 
 - allow to override parametrized fixtures with non-parametrized ones and vice versa (bubenkoff).
 
 - fix issue463: raise specific error for 'parameterize' misspelling (pfctdayelise).
 
 - On failure, the ``sys.last_value``, ``sys.last_type`` and
   ``sys.last_traceback`` are set, so that a user can inspect the error
   via postmortem debugging (almarklein).
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.7.2.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.7.2.rst
@@ -50,9 +50,8 @@ 2.7.2 (compared to 2.7.1)
 - fix issue748: unittest.SkipTest reports to internal pytest unittest plugin.
   Thanks Thomas De Schampheleire for reporting and Bruno Oliveira for the PR.
 
 - fix issue718: failed to create representation of sets containing unsortable
   elements in python 2. Thanks Edison Gustavo Muenz
 
 - fix issue756, fix issue752 (and similar issues): depend on py-1.4.29
   which has a refined algorithm for traceback generation.
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.8.3.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.8.3.rst
@@ -48,12 +48,11 @@ 2.8.3 (compared to 2.8.2)
   belongs to a file which is no longer available.
   Thanks Bruno Oliveira for the PR.
 
 - enhancement made to highlight in red the name of the failing tests so
   they stand out in the output.
   Thanks Gabriel Reis for the PR.
 
 - add more talks to the documentation
-- extend documentation on the --ignore cli option 
-- use pytest-runner for setuptools integration 
+- extend documentation on the --ignore cli option
+- use pytest-runner for setuptools integration
 - minor fixes for interaction with OS X El Capitan system integrity protection (thanks Florian)
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.8.7.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.8.7.rst
@@ -23,9 +23,9 @@ Thanks to all who contributed to this re
 
 Happy testing,
 The py.test Development Team
 
 
 2.8.7 (compared to 2.8.6)
 -------------------------
 
-- fix #1338: use predictable object resolution for monkeypatch
\ No newline at end of file
+- fix #1338: use predictable object resolution for monkeypatch
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.9.0.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.9.0.rst
@@ -9,35 +9,35 @@ See below for the changes and see docs a
     http://pytest.org
 
 As usual, you can upgrade from pypi via::
 
     pip install -U pytest
 
 Thanks to all who contributed to this release, among them:
 
-    Anatoly Bubenkov                                                                                                                                                                                                         
-    Bruno Oliveira                                                                                                                                                                                                           
-    Buck Golemon                                                                                                                                                                                                             
-    David Vierra                                                                                                                                                                                                             
-    Florian Bruhin                                                                                                                                                                                                           
-    Galaczi Endre                                                                                                                                                                                                            
-    Georgy Dyuldin                                                                                                                                                                                                           
-    Lukas Bednar                                                                                                                                                                                                             
-    Luke Murphy                                                                                                                                                                                                              
-    Marcin Biernat                                                                                                                                                                                                           
-    Matt Williams                                                                                                                                                                                                            
-    Michael Aquilina                                                                                                                                                                                                         
-    Raphael Pierzina                                                                                                                                                                                                         
-    Ronny Pfannschmidt                                                                                                                                                                                                       
-    Ryan Wooden                                                                                                                                                                                                              
-    Tiemo Kieft                                                                                                                                                                                                              
-    TomV                                                                                                                                                                                                                     
-    holger krekel                                                                                                                                                                                                            
-    jab   
+    Anatoly Bubenkov
+    Bruno Oliveira
+    Buck Golemon
+    David Vierra
+    Florian Bruhin
+    Galaczi Endre
+    Georgy Dyuldin
+    Lukas Bednar
+    Luke Murphy
+    Marcin Biernat
+    Matt Williams
+    Michael Aquilina
+    Raphael Pierzina
+    Ronny Pfannschmidt
+    Ryan Wooden
+    Tiemo Kieft
+    TomV
+    holger krekel
+    jab
 
 
 Happy testing,
 The py.test Development Team
 
 
 2.9.0 (compared to 2.8.7)
 -------------------------
@@ -71,28 +71,28 @@ 2.9.0 (compared to 2.8.7)
 
 * catch IndexError exceptions when getting exception source location. This fixes
   pytest internal error for dynamically generated code (fixtures and tests)
   where source lines are fake by intention
 
 **Changes**
 
 * **Important**: `py.code <https://pylib.readthedocs.io/en/latest/code.html>`_ has been
-  merged into the ``pytest`` repository as ``pytest._code``. This decision 
-  was made because ``py.code`` had very few uses outside ``pytest`` and the 
-  fact that it was in a different repository made it difficult to fix bugs on 
+  merged into the ``pytest`` repository as ``pytest._code``. This decision
+  was made because ``py.code`` had very few uses outside ``pytest`` and the
+  fact that it was in a different repository made it difficult to fix bugs on
   its code in a timely manner. The team hopes with this to be able to better
   refactor out and improve that code.
   This change shouldn't affect users, but it is useful to let users aware
   if they encounter any strange behavior.
-  
-  Keep in mind that the code for ``pytest._code`` is **private** and 
+
+  Keep in mind that the code for ``pytest._code`` is **private** and
   **experimental**, so you definitely should not import it explicitly!
 
-  Please note that the original ``py.code`` is still available in 
+  Please note that the original ``py.code`` is still available in
   `pylib <https://pylib.readthedocs.io>`_.
 
 * ``pytest_enter_pdb`` now optionally receives the pytest config object.
   Thanks `@nicoddemus`_ for the PR.
 
 * Removed code and documentation for Python 2.5 or lower versions,
   including removal of the obsolete ``_pytest.assertion.oldinterpret`` module.
   Thanks `@nicoddemus`_ for the PR (`#1226`_).
@@ -124,18 +124,18 @@ 2.9.0 (compared to 2.8.7)
   Thanks `@biern`_ for the PR.
 
 * Fix `traceback style docs`_ to describe all of the available options
   (auto/long/short/line/native/no), with `auto` being the default since v2.6.
   Thanks `@hackebrot`_ for the PR.
 
 * Fix (`#1422`_): junit record_xml_property doesn't allow multiple records
   with same name.
-  
-  
+
+
 .. _`traceback style docs`: https://pytest.org/latest/usage.html#modifying-python-traceback-printing
 
 .. _#1422: https://github.com/pytest-dev/pytest/issues/1422
 .. _#1379: https://github.com/pytest-dev/pytest/issues/1379
 .. _#1366: https://github.com/pytest-dev/pytest/issues/1366
 .. _#1040: https://github.com/pytest-dev/pytest/pull/1040
 .. _#680: https://github.com/pytest-dev/pytest/issues/680
 .. _#1287: https://github.com/pytest-dev/pytest/pull/1287
@@ -151,9 +151,9 @@ 2.9.0 (compared to 2.8.7)
 .. _@jab: https://github.com/jab
 .. _@codewarrior0: https://github.com/codewarrior0
 .. _@jaraco: https://github.com/jaraco
 .. _@The-Compiler: https://github.com/The-Compiler
 .. _@Shinkenjoe: https://github.com/Shinkenjoe
 .. _@tomviner: https://github.com/tomviner
 .. _@RonnyPfannschmidt: https://github.com/RonnyPfannschmidt
 .. _@rabbbit: https://github.com/rabbbit
-.. _@hackebrot: https://github.com/hackebrot
\ No newline at end of file
+.. _@hackebrot: https://github.com/hackebrot
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.9.1.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-2.9.1.rst
@@ -9,27 +9,27 @@ See below for the changes and see docs a
     http://pytest.org
 
 As usual, you can upgrade from pypi via::
 
     pip install -U pytest
 
 Thanks to all who contributed to this release, among them:
 
-    Bruno Oliveira                                                                                                                                                                                                                            
-    Daniel Hahler                                                                                                                                                                                                                             
-    Dmitry Malinovsky                                                                                                                                                                                                                         
-    Florian Bruhin                                                                                                                                                                                                                            
-    Floris Bruynooghe                                                                                                                                                                                                                         
-    Matt Bachmann                                                                                                                                                                                                                             
-    Ronny Pfannschmidt                                                                                                                                                                                                                        
-    TomV                                                                                                                                                                                                                                      
-    Vladimir Bolshakov                                                                                                                                                                                                                        
-    Zearin                                                                                                                                                                                                                                     
-    palaviv   
+    Bruno Oliveira
+    Daniel Hahler
+    Dmitry Malinovsky
+    Florian Bruhin
+    Floris Bruynooghe
+    Matt Bachmann
+    Ronny Pfannschmidt
+    TomV
+    Vladimir Bolshakov
+    Zearin
+    palaviv
 
 
 Happy testing,
 The py.test Development Team
 
 
 2.9.1 (compared to 2.9.0)
 -------------------------
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.0.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.0.rst
@@ -3,20 +3,20 @@ pytest-3.0.0
 
 The pytest team is proud to announce the 3.0.0 release!
 
 pytest is a mature Python testing tool with more than a 1600 tests
 against itself, passing on many different interpreters and platforms.
 
 This release contains a lot of bugs fixes and improvements, and much of
 the work done on it was possible because of the 2016 Sprint[1], which
-was funded by an indiegogo campaign which raised over US$12,000 with 
-nearly 100 backers. 
+was funded by an indiegogo campaign which raised over US$12,000 with
+nearly 100 backers.
 
-There's a "What's new in pytest 3.0" [2] blog post highlighting the 
+There's a "What's new in pytest 3.0" [2] blog post highlighting the
 major features in this release.
 
 To see the complete changelog and documentation, please visit:
 
     http://docs.pytest.org
 
 As usual, you can upgrade from pypi via:
 
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.1.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.1.rst
@@ -2,17 +2,17 @@ pytest-3.0.1
 ============
 
 pytest 3.0.1 has just been released to PyPI.
 
 This release fixes some regressions reported in version 3.0.0, being a
 drop-in replacement. To upgrade:
 
   pip install --upgrade pytest
-  
+
 The changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
       Adam Chainz
       Andrew Svetlov
       Bruno Oliveira
       Daniel Hahler
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.2.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.2.rst
@@ -2,17 +2,17 @@ pytest-3.0.2
 ============
 
 pytest 3.0.2 has just been released to PyPI.
 
 This release fixes some regressions and bugs reported in version 3.0.1, being a
 drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
 * Ahn Ki-Wook
 * Bruno Oliveira
 * Florian Bruhin
 * Jordan Guymon
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.3.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.3.rst
@@ -1,18 +1,18 @@
 pytest-3.0.3
 ============
 
 pytest 3.0.3 has just been released to PyPI.
 
-This release fixes some regressions and bugs reported in the last version, 
+This release fixes some regressions and bugs reported in the last version,
 being a drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
 * Bruno Oliveira
 * Florian Bruhin
 * Floris Bruynooghe
 * Huayi Zhang
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.4.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.4.rst
@@ -1,18 +1,18 @@
 pytest-3.0.4
 ============
 
 pytest 3.0.4 has just been released to PyPI.
 
-This release fixes some regressions and bugs reported in the last version, 
+This release fixes some regressions and bugs reported in the last version,
 being a drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
 * Bruno Oliveira
 * Dan Wandschneider
 * Florian Bruhin
 * Georgy Dyuldin
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.5.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.5.rst
@@ -1,17 +1,17 @@
 pytest-3.0.5
 ============
 
 pytest 3.0.5 has just been released to PyPI.
 
 This is a bug-fix release, being a drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
 * Ana Vojnovic
 * Bruno Oliveira
 * Daniel Hahler
 * Duncan Betts
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.6.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.6.rst
@@ -1,17 +1,17 @@
 pytest-3.0.6
 ============
 
 pytest 3.0.6 has just been released to PyPI.
 
 This is a bug-fix release, being a drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 
 Thanks to all who contributed to this release, among them:
 
 * Andreas Pelme
 * Bruno Oliveira
 * Dmitry Malinovsky
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.7.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.0.7.rst
@@ -1,17 +1,17 @@
 pytest-3.0.7
 ============
 
 pytest 3.0.7 has just been released to PyPI.
 
 This is a bug-fix release, being a drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
 * Anthony Sottile
 * Barney Gale
 * Bruno Oliveira
 * Florian Bruhin
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.1.1.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.1.1.rst
@@ -1,17 +1,17 @@
 pytest-3.1.1
 =======================================
 
 pytest 3.1.1 has just been released to PyPI.
 
 This is a bug-fix release, being a drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
 * Bruno Oliveira
 * Florian Bruhin
 * Floris Bruynooghe
 * Jason R. Coombs
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.1.2.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.1.2.rst
@@ -1,17 +1,17 @@
 pytest-3.1.2
 =======================================
 
 pytest 3.1.2 has just been released to PyPI.
 
 This is a bug-fix release, being a drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
 * Andreas Pelme
 * ApaDoctor
 * Bruno Oliveira
 * Florian Bruhin
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.1.3.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.1.3.rst
@@ -1,17 +1,17 @@
 pytest-3.1.3
 =======================================
 
 pytest 3.1.3 has just been released to PyPI.
 
 This is a bug-fix release, being a drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
 * Antoine Legrand
 * Bruno Oliveira
 * Max Moroz
 * Raphael Pierzina
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.1.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.1.rst
@@ -1,17 +1,17 @@
 pytest-3.2.1
 =======================================
 
 pytest 3.2.1 has just been released to PyPI.
 
 This is a bug-fix release, being a drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
 * Alex Gaynor
 * Bruno Oliveira
 * Florian Bruhin
 * Ronny Pfannschmidt
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.2.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.2.rst
@@ -1,17 +1,17 @@
 pytest-3.2.2
 =======================================
 
 pytest 3.2.2 has just been released to PyPI.
 
 This is a bug-fix release, being a drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
 * Andreas Pelme
 * Antonio Hidalgo
 * Bruno Oliveira
 * Felipe Dau
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.3.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.3.rst
@@ -1,17 +1,17 @@
 pytest-3.2.3
 =======================================
 
 pytest 3.2.3 has just been released to PyPI.
 
 This is a bug-fix release, being a drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
 * Bruno Oliveira
 * Evan
 * Joe Hamman
 * Oliver Bestwalter
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.4.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.4.rst
@@ -1,17 +1,17 @@
 pytest-3.2.4
 =======================================
 
 pytest 3.2.4 has just been released to PyPI.
 
 This is a bug-fix release, being a drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
 * Bruno Oliveira
 * Christian Boelsen
 * Christoph Buchner
 * Daw-Ran Liou
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.5.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.2.5.rst
@@ -1,17 +1,17 @@
 pytest-3.2.5
 =======================================
 
 pytest 3.2.5 has just been released to PyPI.
 
 This is a bug-fix release, being a drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
 * Bruno Oliveira
 
 
 Happy testing,
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.3.1.rst
@@ -0,0 +1,25 @@
+pytest-3.3.1
+=======================================
+
+pytest 3.3.1 has just been released to PyPI.
+
+This is a bug-fix release, being a drop-in replacement. To upgrade::
+
+  pip install --upgrade pytest
+
+The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
+
+Thanks to all who contributed to this release, among them:
+
+* Bruno Oliveira
+* Daniel Hahler
+* Eugene Prikazchikov
+* Florian Bruhin
+* Roland Puntaier
+* Ronny Pfannschmidt
+* Sebastian Rahlf
+* Tom Viner
+
+
+Happy testing,
+The pytest Development Team
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.3.2.rst
@@ -0,0 +1,28 @@
+pytest-3.3.2
+=======================================
+
+pytest 3.3.2 has just been released to PyPI.
+
+This is a bug-fix release, being a drop-in replacement. To upgrade::
+
+  pip install --upgrade pytest
+
+The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
+
+Thanks to all who contributed to this release, among them:
+
+* Anthony Sottile
+* Antony Lee
+* Austin
+* Bruno Oliveira
+* Florian Bruhin
+* Floris Bruynooghe
+* Henk-Jaap Wagenaar
+* Jurko Gospodnetić
+* Ronny Pfannschmidt
+* Srinivas Reddy Thatiparthy
+* Thomas Hisch
+
+
+Happy testing,
+The pytest Development Team
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.4.0.rst
@@ -0,0 +1,52 @@
+pytest-3.4.0
+=======================================
+
+The pytest team is proud to announce the 3.4.0 release!
+
+pytest is a mature Python testing tool with more than a 1600 tests
+against itself, passing on many different interpreters and platforms.
+
+This release contains a number of bugs fixes and improvements, so users are encouraged
+to take a look at the CHANGELOG:
+
+    http://doc.pytest.org/en/latest/changelog.html
+
+For complete documentation, please visit:
+
+    http://docs.pytest.org
+
+As usual, you can upgrade from pypi via:
+
+    pip install -U pytest
+
+Thanks to all who contributed to this release, among them:
+
+* Aaron
+* Alan Velasco
+* Anders Hovmöller
+* Andrew Toolan
+* Anthony Sottile
+* Aron Coyle
+* Brian Maissy
+* Bruno Oliveira
+* Cyrus Maden
+* Florian Bruhin
+* Henk-Jaap Wagenaar
+* Ian Lesperance
+* Jon Dufresne
+* Jurko Gospodnetić
+* Kate
+* Kimberly
+* Per A. Brodtkorb
+* Pierre-Alexandre Fonta
+* Raphael Castaneda
+* Ronny Pfannschmidt
+* ST John
+* Segev Finer
+* Thomas Hisch
+* Tzu-ping Chung
+* feuillemorte
+
+
+Happy testing,
+The Pytest Development Team
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.4.1.rst
@@ -0,0 +1,27 @@
+pytest-3.4.1
+=======================================
+
+pytest 3.4.1 has just been released to PyPI.
+
+This is a bug-fix release, being a drop-in replacement. To upgrade::
+
+  pip install --upgrade pytest
+
+The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
+
+Thanks to all who contributed to this release, among them:
+
+* Aaron
+* Alan Velasco
+* Andy Freeland
+* Brian Maissy
+* Bruno Oliveira
+* Florian Bruhin
+* Jason R. Coombs
+* Marcin Bachry
+* Pedro Algarvio
+* Ronny Pfannschmidt
+
+
+Happy testing,
+The pytest Development Team
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.4.2.rst
@@ -0,0 +1,28 @@
+pytest-3.4.2
+=======================================
+
+pytest 3.4.2 has just been released to PyPI.
+
+This is a bug-fix release, being a drop-in replacement. To upgrade::
+
+  pip install --upgrade pytest
+
+The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
+
+Thanks to all who contributed to this release, among them:
+
+* Allan Feldman
+* Bruno Oliveira
+* Florian Bruhin
+* Jason R. Coombs
+* Kyle Altendorf
+* Maik Figura
+* Ronny Pfannschmidt
+* codetriage-readme-bot
+* feuillemorte
+* joshm91
+* mike
+
+
+Happy testing,
+The pytest Development Team
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.5.0.rst
@@ -0,0 +1,51 @@
+pytest-3.5.0
+=======================================
+
+The pytest team is proud to announce the 3.5.0 release!
+
+pytest is a mature Python testing tool with more than a 1600 tests
+against itself, passing on many different interpreters and platforms.
+
+This release contains a number of bugs fixes and improvements, so users are encouraged
+to take a look at the CHANGELOG:
+
+    http://doc.pytest.org/en/latest/changelog.html
+
+For complete documentation, please visit:
+
+    http://docs.pytest.org
+
+As usual, you can upgrade from pypi via:
+
+    pip install -U pytest
+
+Thanks to all who contributed to this release, among them:
+
+* Allan Feldman
+* Brian Maissy
+* Bruno Oliveira
+* Carlos Jenkins
+* Daniel Hahler
+* Florian Bruhin
+* Jason R. Coombs
+* Jeffrey Rackauckas
+* Jordan Speicher
+* Julien Palard
+* Kale Kundert
+* Kostis Anagnostopoulos
+* Kyle Altendorf
+* Maik Figura
+* Pedro Algarvio
+* Ronny Pfannschmidt
+* Tadeu Manoel
+* Tareq Alayan
+* Thomas Hisch
+* William Lee
+* codetriage-readme-bot
+* feuillemorte
+* joshm91
+* mike
+
+
+Happy testing,
+The Pytest Development Team
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.5.1.rst
@@ -0,0 +1,30 @@
+pytest-3.5.1
+=======================================
+
+pytest 3.5.1 has just been released to PyPI.
+
+This is a bug-fix release, being a drop-in replacement. To upgrade::
+
+  pip install --upgrade pytest
+
+The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
+
+Thanks to all who contributed to this release, among them:
+
+* Brian Maissy
+* Bruno Oliveira
+* Darren Burns
+* David Chudzicki
+* Floris Bruynooghe
+* Holger Kohr
+* Irmen de Jong
+* Jeffrey Rackauckas
+* Rachel Kogan
+* Ronny Pfannschmidt
+* Stefan Scherfke
+* Tim Strazny
+* Семён Марьясин
+
+
+Happy testing,
+The pytest Development Team
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.6.0.rst
@@ -0,0 +1,41 @@
+pytest-3.6.0
+=======================================
+
+The pytest team is proud to announce the 3.6.0 release!
+
+pytest is a mature Python testing tool with more than a 1600 tests
+against itself, passing on many different interpreters and platforms.
+
+This release contains a number of bugs fixes and improvements, so users are encouraged
+to take a look at the CHANGELOG:
+
+    http://doc.pytest.org/en/latest/changelog.html
+
+For complete documentation, please visit:
+
+    http://docs.pytest.org
+
+As usual, you can upgrade from pypi via:
+
+    pip install -U pytest
+
+Thanks to all who contributed to this release, among them:
+
+* Anthony Shaw
+* ApaDoctor
+* Brian Maissy
+* Bruno Oliveira
+* Jon Dufresne
+* Katerina Koukiou
+* Miro Hrončok
+* Rachel Kogan
+* Ronny Pfannschmidt
+* Tim Hughes
+* Tyler Goodlet
+* Ville Skyttä
+* aviral1701
+* feuillemorte
+
+
+Happy testing,
+The Pytest Development Team
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.6.1.rst
@@ -0,0 +1,24 @@
+pytest-3.6.1
+=======================================
+
+pytest 3.6.1 has just been released to PyPI.
+
+This is a bug-fix release, being a drop-in replacement. To upgrade::
+
+  pip install --upgrade pytest
+
+The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
+
+Thanks to all who contributed to this release, among them:
+
+* Anthony Sottile
+* Bruno Oliveira
+* Jeffrey Rackauckas
+* Miro Hrončok
+* Niklas Meinzer
+* Oliver Bestwalter
+* Ronny Pfannschmidt
+
+
+Happy testing,
+The pytest Development Team
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/announce/release-3.6.2.rst
@@ -0,0 +1,29 @@
+pytest-3.6.2
+=======================================
+
+pytest 3.6.2 has just been released to PyPI.
+
+This is a bug-fix release, being a drop-in replacement. To upgrade::
+
+  pip install --upgrade pytest
+
+The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
+
+Thanks to all who contributed to this release, among them:
+
+* Alan Velasco
+* Alex Barbato
+* Anthony Sottile
+* Bartosz Cierocki
+* Bruno Oliveira
+* Daniel Hahler
+* Guoqiang Zhang
+* Hynek Schlawack
+* John T. Wodder II
+* Michael Käufl
+* Ronny Pfannschmidt
+* Samuel Dion-Girardeau
+
+
+Happy testing,
+The pytest Development Team
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/assert.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/assert.rst
@@ -24,27 +24,27 @@ following::
 to assert that your function returns a certain value. If this assertion fails
 you will see the return value of the function call::
 
     $ pytest test_assert1.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 1 item
-    
+
     test_assert1.py F                                                    [100%]
-    
+
     ================================= FAILURES =================================
     ______________________________ test_function _______________________________
-    
+
         def test_function():
     >       assert f() == 4
     E       assert 3 == 4
     E        +  where 3 = f()
-    
+
     test_assert1.py:5: AssertionError
     ========================= 1 failed in 0.12 seconds =========================
 
 ``pytest`` has support for showing the values of the most common subexpressions
 including calls, attributes, comparisons, and binary and unary
 operators. (See :ref:`tbreportdemo`).  This allows you to use the
 idiomatic python constructs without boilerplate code while not losing
 introspection information.
@@ -86,17 +86,17 @@ the actual exception raised.  The main a
 ``.type``, ``.value`` and ``.traceback``.
 
 .. versionchanged:: 3.0
 
 In the context manager form you may use the keyword argument
 ``message`` to specify a custom failure message::
 
      >>> with raises(ZeroDivisionError, message="Expecting ZeroDivisionError"):
-     ...    pass
+     ...     pass
      ... Failed: Expecting ZeroDivisionError
 
 If you want to write test code that works on Python 2.4 as well,
 you may also use two other ways to test for an expected exception::
 
     pytest.raises(ExpectedException, func, *args, **kwargs)
     pytest.raises(ExpectedException, "func(*args, **kwargs)")
 
@@ -167,33 +167,33 @@ when it encounters comparisons.  For exa
 
 if you run this module::
 
     $ pytest test_assert2.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 1 item
-    
+
     test_assert2.py F                                                    [100%]
-    
+
     ================================= FAILURES =================================
     ___________________________ test_set_comparison ____________________________
-    
+
         def test_set_comparison():
             set1 = set("1308")
             set2 = set("8035")
     >       assert set1 == set2
     E       AssertionError: assert {'0', '1', '3', '8'} == {'0', '3', '5', '8'}
     E         Extra items in the left set:
     E         '1'
     E         Extra items in the right set:
     E         '5'
     E         Use -v to get the full diff
-    
+
     test_assert2.py:5: AssertionError
     ========================= 1 failed in 0.12 seconds =========================
 
 Special comparisons are done for a number of cases:
 
 * comparing long strings: a context diff is shown
 * comparing long sequences: first failing indices
 * comparing dicts: different entries
@@ -204,17 +204,17 @@ Defining your own assertion comparison
 ----------------------------------------------
 
 It is possible to add your own detailed explanations by implementing
 the ``pytest_assertrepr_compare`` hook.
 
 .. autofunction:: _pytest.hookspec.pytest_assertrepr_compare
    :noindex:
 
-As an example consider adding the following hook in a :ref:`conftest.py <conftest.py>` 
+As an example consider adding the following hook in a :ref:`conftest.py <conftest.py>`
 file which provides an alternative explanation for ``Foo`` objects::
 
    # content of conftest.py
    from test_foocompare import Foo
    def pytest_assertrepr_compare(op, left, right):
        if isinstance(left, Foo) and isinstance(right, Foo) and op == "==":
            return ['Comparing Foo instances:',
                    '   vals: %s != %s' % (left.val, right.val)]
@@ -236,24 +236,24 @@ now, given this test module::
 
 you can run the test module and get the custom output defined in
 the conftest file::
 
    $ pytest -q test_foocompare.py
    F                                                                    [100%]
    ================================= FAILURES =================================
    _______________________________ test_compare _______________________________
-   
+
        def test_compare():
            f1 = Foo(1)
            f2 = Foo(2)
    >       assert f1 == f2
    E       assert Comparing Foo instances:
    E            vals: 1 != 2
-   
+
    test_foocompare.py:11: AssertionError
    1 failed in 0.12 seconds
 
 .. _assert-details:
 .. _`assert introspection`:
 
 Advanced assertion introspection
 ----------------------------------
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/backwards-compatibility.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/backwards-compatibility.rst
@@ -10,96 +10,11 @@ With the pytest 3.0 release we introduce
 To communicate changes we are already issuing deprecation warnings, but they are not displayed by default. In pytest 3.0 we changed the default setting so that pytest deprecation warnings are displayed if not explicitly silenced (with ``--disable-pytest-warnings``).
 
 We will only remove deprecated functionality in major releases (e.g. if we deprecate something in 3.0 we will remove it in 4.0), and keep it around for at least two minor releases (e.g. if we deprecate something in 3.9 and 4.0 is the next release, we will not remove it in 4.0 but in 5.0).
 
 
 Deprecation Roadmap
 -------------------
 
-This page lists deprecated features and when we plan to remove them. It is important to list the feature, the version where it got deprecated and the version we plan to remove it.
-
-Following our deprecation policy, we should aim to keep features for *at least* two minor versions after it was considered deprecated.
-
-
-Future Releases
-~~~~~~~~~~~~~~~
-
-3.4
-^^^
-
-**Old style classes**
-
-Issue: `#2147 <https://github.com/pytest-dev/pytest/issues/2147>`_.
-
-Deprecated in ``3.2``.
-
-4.0
-^^^
-
-**Yield tests**
-
-Deprecated in ``3.0``.
-
-**pytest-namespace hook**
-
-deprecated in ``3.2``.
-
-**Marks in parameter sets**
-
-Deprecated in ``3.2``.
-
-**--result-log**
-
-Deprecated in ``3.0``.
-
-See `#830 <https://github.com/pytest-dev/pytest/issues/830>`_ for more information. Suggested alternative: `pytest-tap <https://pypi.python.org/pypi/pytest-tap>`_.
-
-**metafunc.addcall**
-
-Issue: `#2876 <https://github.com/pytest-dev/pytest/issues/2876>`_.
-
-Deprecated in ``3.3``.
+We track deprecation and removal of features using milestones and the `deprecation <https://github.com/pytest-dev/pytest/issues?q=label%3A%22type%3A+deprecation%22>`_ and `removal <https://github.com/pytest-dev/pytest/labels/type%3A%20removal>`_ labels on GitHub.
 
-**pytest_plugins in non-toplevel conftests**
-
-There is a deep conceptual confusion as ``conftest.py`` files themselves are activated/deactivated based on path, but the plugins they depend on aren't.
-
-Issue: `#2639 <https://github.com/pytest-dev/pytest/issues/2639>`_.
-
-Not yet officially deprecated.
-
-**passing a single string to pytest.main()**
-
-Pass a list of strings to ``pytest.main()`` instead.
-
-Deprecated in ``3.1``.
-
-**[pytest] section in setup.cfg**
-
-Use ``[tool:pytest]`` instead for compatibility with other tools.
-
-Deprecated in ``3.0``.
-
-Past Releases
-~~~~~~~~~~~~~
-
-3.0
-^^^
-
-* The following deprecated commandline options were removed:
-
-  * ``--genscript``: no longer supported;
-  * ``--no-assert``: use ``--assert=plain`` instead;
-  * ``--nomagic``: use ``--assert=plain`` instead;
-  * ``--report``: use ``-r`` instead;
-
-* Removed all ``py.test-X*`` entry points. The versioned, suffixed entry points
-  were never documented and a leftover from a pre-virtualenv era. These entry
-  points also created broken entry points in wheels, so removing them also
-  removes a source of confusion for users.
-
-
-
-3.3
-^^^
-
-* Dropped support for EOL Python 2.6 and 3.3.
\ No newline at end of file
+Following our deprecation policy, after starting issuing deprecation warnings we keep features for *at least* two minor versions before considering removal.
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/bash-completion.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/bash-completion.rst
@@ -9,20 +9,17 @@ When using bash as your shell, ``pytest`
 For this ``argcomplete`` needs to be installed **and** enabled.
 
 Install argcomplete using::
 
         sudo pip install 'argcomplete>=0.5.7'
 
 For global activation of all argcomplete enabled python applications run::
 
-	sudo activate-global-python-argcomplete
+    sudo activate-global-python-argcomplete
 
 For permanent (but not global) ``pytest`` activation, use::
 
         register-python-argcomplete pytest >> ~/.bashrc
 
 For one-time activation of argcomplete for ``pytest`` only, use::
 
         eval "$(register-python-argcomplete pytest)"
-
-
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/builtin.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/builtin.rst
@@ -1,161 +1,122 @@
+:orphan:
 
 .. _`pytest helpers`:
 
 Pytest API and builtin fixtures
 ================================================
 
-This is a list of ``pytest.*`` API functions and fixtures.
+
+Most of the information of this page has been moved over to :ref:`reference`.
 
 For information on plugin hooks and objects, see :ref:`plugins`.
 
 For information on the ``pytest.mark`` mechanism, see :ref:`mark`.
 
-For the below objects, you can also interactively ask for help, e.g. by
-typing on the Python interactive prompt something like::
-
-    import pytest
-    help(pytest)
-
-.. currentmodule:: pytest
-
-Invoking pytest interactively
----------------------------------------------------
-
-.. autofunction:: main
-
-More examples at :ref:`pytest.main-usage`
-
-
-Helpers for assertions about Exceptions/Warnings
---------------------------------------------------------
-
-.. autofunction:: raises
-
-Examples at :ref:`assertraises`.
-
-.. autofunction:: deprecated_call
-
-Comparing floating point numbers
---------------------------------
-
-.. autofunction:: approx
-
-Raising a specific test outcome
---------------------------------------
-
-You can use the following functions in your test, fixture or setup
-functions to force a certain test outcome.  Note that most often
-you can rather use declarative marks, see :ref:`skipping`.
-
-.. autofunction:: _pytest.outcomes.fail
-.. autofunction:: _pytest.outcomes.skip
-.. autofunction:: _pytest.outcomes.importorskip
-.. autofunction:: _pytest.outcomes.xfail
-.. autofunction:: _pytest.outcomes.exit
-
-Fixtures and requests
------------------------------------------------------
-
-To mark a fixture function:
-
-.. autofunction:: _pytest.fixtures.fixture
-
-Tutorial at :ref:`fixtures`.
-
-The ``request`` object that can be used from fixture functions.
-
-.. autoclass:: _pytest.fixtures.FixtureRequest()
-    :members:
-
-
-.. _builtinfixtures:
-.. _builtinfuncargs:
-
-Builtin fixtures/function arguments
------------------------------------------
-
-You can ask for available builtin or project-custom
-:ref:`fixtures <fixtures>` by typing::
+For information about fixtures, see :ref:`fixtures`. To see a complete list of available fixtures (add ``-v`` to also see fixtures with leading ``_``), type ::
 
     $ pytest -q --fixtures
     cache
         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.
     capsys
-        Enable capturing of writes to sys.stdout/sys.stderr and make
+        Enable capturing of writes to ``sys.stdout`` and ``sys.stderr`` and make
         captured output available via ``capsys.readouterr()`` method calls
-        which return a ``(out, err)`` tuple.  ``out`` and ``err`` will be ``text``
+        which return a ``(out, err)`` namedtuple.  ``out`` and ``err`` will be ``text``
         objects.
     capsysbinary
-        Enable capturing of writes to sys.stdout/sys.stderr and make
+        Enable capturing of writes to ``sys.stdout`` and ``sys.stderr`` and make
         captured output available via ``capsys.readouterr()`` method calls
         which return a ``(out, err)`` tuple.  ``out`` and ``err`` will be ``bytes``
         objects.
     capfd
-        Enable capturing of writes to file descriptors 1 and 2 and make
+        Enable capturing of writes to file descriptors ``1`` and ``2`` and make
         captured output available via ``capfd.readouterr()`` method calls
         which return a ``(out, err)`` tuple.  ``out`` and ``err`` will be ``text``
         objects.
     capfdbinary
         Enable capturing of write to file descriptors 1 and 2 and make
         captured output available via ``capfdbinary.readouterr`` method calls
         which return a ``(out, err)`` tuple.  ``out`` and ``err`` will be
         ``bytes`` objects.
     doctest_namespace
-        Inject names into the doctest namespace.
+        Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.
     pytestconfig
-        the pytest config object with access to command line opts.
-    record_xml_property
-        Add extra xml properties to the tag for the calling test.
+        Session-scoped fixture that returns the :class:`_pytest.config.Config` object.
+
+        Example::
+
+            def test_foo(pytestconfig):
+                if pytestconfig.getoption("verbose"):
+                    ...
+    record_property
+        Add an extra properties the calling test.
+        User properties become part of the test report and are available to the
+        configured reporters, like JUnit XML.
         The fixture is callable with ``(name, value)``, with value being automatically
         xml-encoded.
+
+        Example::
+
+            def test_function(record_property):
+                record_property("example_key", 1)
+    record_xml_property
+        (Deprecated) use record_property.
+    record_xml_attribute
+        Add extra xml attributes to the tag for the calling test.
+        The fixture is callable with ``(name, value)``, with value being
+        automatically xml-encoded
     caplog
         Access and control log capturing.
-        
+
         Captured logs are available through the following methods::
-        
-        * caplog.text()          -> string containing formatted log output
-        * caplog.records()       -> list of logging.LogRecord instances
-        * caplog.record_tuples() -> list of (logger_name, level, message) tuples
+
+        * caplog.text            -> string containing formatted log output
+        * caplog.records         -> list of logging.LogRecord instances
+        * caplog.record_tuples   -> list of (logger_name, level, message) tuples
+        * caplog.clear()         -> clear captured records and formatted log output string
     monkeypatch
         The returned ``monkeypatch`` fixture provides these
         helper methods to modify objects, dictionaries or os.environ::
-        
+
             monkeypatch.setattr(obj, name, value, raising=True)
             monkeypatch.delattr(obj, name, raising=True)
             monkeypatch.setitem(mapping, name, value)
             monkeypatch.delitem(obj, name, raising=True)
             monkeypatch.setenv(name, value, prepend=False)
             monkeypatch.delenv(name, value, raising=True)
             monkeypatch.syspath_prepend(path)
             monkeypatch.chdir(path)
-        
+
         All modifications will be undone after the requesting
         test function or fixture has finished. The ``raising``
         parameter determines if a KeyError or AttributeError
         will be raised if the set/deletion operation has no target.
     recwarn
-        Return a WarningsRecorder instance that provides these methods:
-        
-        * ``pop(category=None)``: return last warning matching the category.
-        * ``clear()``: clear list of warnings
-        
+        Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.
+
         See http://docs.python.org/library/warnings.html for information
         on warning categories.
     tmpdir_factory
         Return a TempdirFactory instance for the test session.
     tmpdir
         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`_
         path object.
-    
+
+        .. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html
+
     no tests ran in 0.12 seconds
+
+You can also interactively ask for help, e.g. by typing on the Python interactive prompt something like::
+
+    import pytest
+    help(pytest)
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/cache.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/cache.rst
@@ -15,17 +15,17 @@ last ``pytest`` invocation:
 
 * ``--lf``, ``--last-failed`` - to only re-run the failures.
 * ``--ff``, ``--failed-first`` - to run the failures first and then the rest of
   the tests.
 
 For cleanup (usually not needed), a ``--cache-clear`` option allows to remove
 all cross-session cache contents ahead of a test run.
 
-Other plugins may access the `config.cache`_ object to set/get 
+Other plugins may access the `config.cache`_ object to set/get
 **json encodable** values between ``pytest`` invocations.
 
 .. note::
 
     This plugin is enabled by default, but can be disabled if needed: see
     :ref:`cmdunregister` (the internal name for this plugin is
     ``cacheprovider``).
 
@@ -44,119 +44,132 @@ First, let's create 50 test invocation o
            pytest.fail("bad luck")
 
 If you run this for the first time you will see two failures::
 
     $ pytest -q
     .................F.......F........................                   [100%]
     ================================= FAILURES =================================
     _______________________________ test_num[17] _______________________________
-    
+
     i = 17
-    
+
         @pytest.mark.parametrize("i", range(50))
         def test_num(i):
             if i in (17, 25):
     >          pytest.fail("bad luck")
     E          Failed: bad luck
-    
+
     test_50.py:6: Failed
     _______________________________ test_num[25] _______________________________
-    
+
     i = 25
-    
+
         @pytest.mark.parametrize("i", range(50))
         def test_num(i):
             if i in (17, 25):
     >          pytest.fail("bad luck")
     E          Failed: bad luck
-    
+
     test_50.py:6: Failed
     2 failed, 48 passed in 0.12 seconds
 
 If you then run it with ``--lf``::
 
     $ pytest --lf
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
-    collected 50 items
+    collected 50 items / 48 deselected
     run-last-failure: rerun previous 2 failures
-    
+
     test_50.py FF                                                        [100%]
-    
+
     ================================= FAILURES =================================
     _______________________________ test_num[17] _______________________________
-    
+
     i = 17
-    
+
         @pytest.mark.parametrize("i", range(50))
         def test_num(i):
             if i in (17, 25):
     >          pytest.fail("bad luck")
     E          Failed: bad luck
-    
+
     test_50.py:6: Failed
     _______________________________ test_num[25] _______________________________
-    
+
     i = 25
-    
+
         @pytest.mark.parametrize("i", range(50))
         def test_num(i):
             if i in (17, 25):
     >          pytest.fail("bad luck")
     E          Failed: bad luck
-    
+
     test_50.py:6: Failed
-    =========================== 48 tests deselected ============================
     ================= 2 failed, 48 deselected in 0.12 seconds ==================
 
 You have run only the two failing test from the last run, while 48 tests have
 not been run ("deselected").
 
 Now, if you run with the ``--ff`` option, all tests will be run but the first
 previous failures will be executed first (as can be seen from the series
 of ``FF`` and dots)::
 
     $ pytest --ff
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 50 items
     run-last-failure: rerun previous 2 failures first
-    
+
     test_50.py FF................................................        [100%]
-    
+
     ================================= FAILURES =================================
     _______________________________ test_num[17] _______________________________
-    
+
     i = 17
-    
+
         @pytest.mark.parametrize("i", range(50))
         def test_num(i):
             if i in (17, 25):
     >          pytest.fail("bad luck")
     E          Failed: bad luck
-    
+
     test_50.py:6: Failed
     _______________________________ test_num[25] _______________________________
-    
+
     i = 25
-    
+
         @pytest.mark.parametrize("i", range(50))
         def test_num(i):
             if i in (17, 25):
     >          pytest.fail("bad luck")
     E          Failed: bad luck
-    
+
     test_50.py:6: Failed
     =================== 2 failed, 48 passed in 0.12 seconds ====================
 
 .. _`config.cache`:
 
+New ``--nf``, ``--new-first`` options: run new tests first followed by the rest
+of the tests, in both cases tests are also sorted by the file modified time,
+with more recent files coming first.
+
+Behavior when no tests failed in the last run
+---------------------------------------------
+
+When no tests failed in the last run, or when no cached ``lastfailed`` data was
+found, ``pytest`` can be configured either to run all of the tests or no tests,
+using the ``--last-failed-no-failures`` option, which takes one of the following values::
+
+    pytest --last-failed-no-failures all    # run all tests (default behavior)
+    pytest --last-failed-no-failures none   # run no tests and exit
+
 The new config.cache object
 --------------------------------
 
 .. regendoc:wipe
 
 Plugins or conftest.py support code can get a cached value using the
 pytest ``config`` object.  Here is a basic example plugin which
 implements a :ref:`fixture` which re-uses previously created state
@@ -180,89 +193,70 @@ across pytest invocations::
 
 If you run this command once, it will take a while because
 of the sleep::
 
     $ pytest -q
     F                                                                    [100%]
     ================================= FAILURES =================================
     ______________________________ test_function _______________________________
-    
+
     mydata = 42
-    
+
         def test_function(mydata):
     >       assert mydata == 23
     E       assert 42 == 23
-    
+
     test_caching.py:14: AssertionError
     1 failed in 0.12 seconds
 
 If you run it a second time the value will be retrieved from
 the cache and this will be quick::
 
     $ pytest -q
     F                                                                    [100%]
     ================================= FAILURES =================================
     ______________________________ test_function _______________________________
-    
+
     mydata = 42
-    
+
         def test_function(mydata):
     >       assert mydata == 23
     E       assert 42 == 23
-    
+
     test_caching.py:14: AssertionError
     1 failed in 0.12 seconds
 
-See the `cache-api`_ for more details.
+See the :ref:`cache-api` for more details.
 
 
 Inspecting Cache content
 -------------------------------
 
 You can always peek at the content of the cache using the
 ``--cache-show`` command line option::
 
-    $ py.test --cache-show
+    $ pytest --cache-show
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
-    cachedir: $REGENDOC_TMPDIR/.cache
+    cachedir: $REGENDOC_TMPDIR/.pytest_cache
     ------------------------------- cache values -------------------------------
     cache/lastfailed contains:
       {'test_caching.py::test_function': True}
+    cache/nodeids contains:
+      ['test_caching.py::test_function']
     example/value contains:
       42
-    
+
     ======================= no tests ran in 0.12 seconds =======================
 
 Clearing Cache content
 -------------------------------
 
 You can instruct pytest to clear all cache files and values
 by adding the ``--cache-clear`` option like this::
 
     pytest --cache-clear
 
 This is recommended for invocations from Continuous Integration
 servers where isolation and correctness is more important
 than speed.
-
-
-.. _`cache-api`:
-
-config.cache API
-------------------
-
-The ``config.cache`` object allows other plugins,
-including ``conftest.py`` files,
-to safely and flexibly store and retrieve values across
-test runs because the ``config`` object is available
-in many places.
-
-Under the hood, the cache plugin uses the simple
-dumps/loads API of the json stdlib module
-
-.. currentmodule:: _pytest.cacheprovider
-
-.. automethod:: Cache.get
-.. automethod:: Cache.set
-.. automethod:: Cache.makedir
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/capture.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/capture.rst
@@ -4,17 +4,18 @@
 Capturing of the stdout/stderr output
 =========================================================
 
 Default stdout/stderr/stdin capturing behaviour
 ---------------------------------------------------------
 
 During test execution any output sent to ``stdout`` and ``stderr`` is
 captured.  If a test or a setup method fails its according captured
-output will usually be shown along with the failure traceback.
+output will usually be shown along with the failure traceback. (this
+behavior can be configured by the ``--show-capture`` command-line option).
 
 In addition, ``stdin`` is set to a "null" object which will
 fail on attempts to read from it because it is rarely desired
 to wait for interactive input when running automated tests.
 
 By default capturing is done by intercepting writes to low level
 file descriptors.  This allows to capture output from simple
 print statements as well as output from a subprocess started by
@@ -62,49 +63,49 @@ is that you can use print statements for
 and running this module will show you precisely the output
 of the failing function and hide the other one::
 
     $ pytest
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 2 items
-    
+
     test_module.py .F                                                    [100%]
-    
+
     ================================= FAILURES =================================
     ________________________________ test_func2 ________________________________
-    
+
         def test_func2():
     >       assert False
     E       assert False
-    
+
     test_module.py:9: AssertionError
     -------------------------- Captured stdout setup ---------------------------
     setting up <function test_func2 at 0xdeadbeef>
     ==================== 1 failed, 1 passed in 0.12 seconds ====================
 
 Accessing captured output from a test function
 ---------------------------------------------------
 
 The ``capsys``, ``capsysbinary``, ``capfd``, and ``capfdbinary`` fixtures
 allow access to stdout/stderr output created during test execution.  Here is
 an example test function that performs some output related checks:
 
 .. code-block:: python
 
-    def test_myoutput(capsys): # or use "capfd" for fd-level
-        print ("hello")
+    def test_myoutput(capsys):  # or use "capfd" for fd-level
+        print("hello")
         sys.stderr.write("world\n")
-        out, err = capsys.readouterr()
-        assert out == "hello\n"
-        assert err == "world\n"
-        print ("next")
-        out, err = capsys.readouterr()
-        assert out == "next\n"
+        captured = capsys.readouterr()
+        assert captured.out == "hello\n"
+        assert captured.err == "world\n"
+        print("next")
+        captured = capsys.readouterr()
+        assert captured.out == "next\n"
 
 The ``readouterr()`` call snapshots the output so far -
 and capturing will be continued.  After the test
 function finishes the original streams will
 be restored.  Using ``capsys`` this way frees your
 test from having to care about setting/resetting
 output streams and also interacts well with pytest's
 own per-test capturing.
@@ -112,16 +113,20 @@ own per-test capturing.
 If you want to capture on filedescriptor level you can use
 the ``capfd`` fixture which offers the exact
 same interface but allows to also capture output from
 libraries or subprocesses that directly write to operating
 system level output streams (FD1 and FD2).
 
 .. versionadded:: 3.3
 
+The return value from ``readouterr`` changed to a ``namedtuple`` with two attributes, ``out`` and ``err``.
+
+.. versionadded:: 3.3
+
 If the code under test writes non-textual data, you can capture this using
 the ``capsysbinary`` fixture which instead returns ``bytes`` from
 the ``readouterr`` method.  The ``capfsysbinary`` fixture is currently only
 available in python 3.
 
 
 .. versionadded:: 3.3
 
@@ -135,14 +140,14 @@ filedescriptor level.
 
 To temporarily disable capture within a test, both ``capsys``
 and ``capfd`` have a ``disabled()`` method that can be used
 as a context manager, disabling capture inside the ``with`` block:
 
 .. code-block:: python
 
     def test_disabling_capturing(capsys):
-        print('this output is captured')
+        print("this output is captured")
         with capsys.disabled():
-            print('output not captured, going directly to sys.stdout')
-        print('this output is also captured')
+            print("output not captured, going directly to sys.stdout")
+        print("this output is also captured")
 
 .. include:: links.inc
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/check_sphinx.py
+++ /dev/null
@@ -1,17 +0,0 @@
-import py
-import subprocess
-def test_build_docs(tmpdir):
-    doctrees = tmpdir.join("doctrees")
-    htmldir = tmpdir.join("html")
-    subprocess.check_call([
-        "sphinx-build", "-W", "-bhtml",
-          "-d", str(doctrees), ".", str(htmldir)])
-
-def test_linkcheck(tmpdir):
-    doctrees = tmpdir.join("doctrees")
-    htmldir = tmpdir.join("html")
-    subprocess.check_call(
-        ["sphinx-build", "-blinkcheck",
-          "-d", str(doctrees), ".", str(htmldir)])
-
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/conf.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/conf.py
@@ -13,123 +13,134 @@
 
 # The version info for the project you're documenting, acts as replacement for
 # |version| and |release|, also used in various other places throughout the
 # built documents.
 #
 # The full version, including alpha/beta/rc tags.
 # The short X.Y version.
 
-import os, sys
+import os
+import sys
+import datetime
+
 from _pytest import __version__ as version
+
 release = ".".join(version.split(".")[:2])
 
 # If extensions (or modules to document with autodoc) are in another directory,
 # add these directories to sys.path here. If the directory is relative to the
 # documentation root, use os.path.abspath to make it absolute, like shown here.
-#sys.path.insert(0, os.path.abspath('.'))
+# sys.path.insert(0, os.path.abspath('.'))
 
 autodoc_member_order = "bysource"
 todo_include_todos = 1
 
 # -- General configuration -----------------------------------------------------
 
 # If your documentation needs a minimal Sphinx version, state it here.
-#needs_sphinx = '1.0'
+# needs_sphinx = '1.0'
 
 # Add any Sphinx extension module names here, as strings. They can be extensions
 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.autosummary',
-    'sphinx.ext.intersphinx', 'sphinx.ext.viewcode']
+extensions = [
+    "sphinx.ext.autodoc",
+    "sphinx.ext.todo",
+    "sphinx.ext.autosummary",
+    "sphinx.ext.intersphinx",
+    "sphinx.ext.viewcode",
+    "sphinxcontrib_trio",
+]
 
 # Add any paths that contain templates here, relative to this directory.
-templates_path = ['_templates']
+templates_path = ["_templates"]
 
 # The suffix of source filenames.
-source_suffix = '.rst'
+source_suffix = ".rst"
 
 # The encoding of source files.
-#source_encoding = 'utf-8-sig'
+# source_encoding = 'utf-8-sig'
 
 # The master toctree document.
-master_doc = 'contents'
+master_doc = "contents"
 
 # General information about the project.
-project = u'pytest'
-copyright = u'2015, holger krekel and pytest-dev team'
-
+project = u"pytest"
+year = datetime.datetime.utcnow().year
+copyright = u"2015–{} , holger krekel and pytest-dev team".format(year)
 
 
 # The language for content autogenerated by Sphinx. Refer to documentation
 # for a list of supported languages.
-#language = None
+# language = None
 
 # There are two options for replacing |today|: either, you set today to some
 # non-false value, then it is used:
-#today = ''
+# today = ''
 # Else, today_fmt is used as the format for a strftime call.
-#today_fmt = '%B %d, %Y'
+# today_fmt = '%B %d, %Y'
 
 # List of patterns, relative to source directory, that match files and
 # directories to ignore when looking for source files.
-exclude_patterns = ['links.inc', '_build', 'naming20.rst', 'test/*',
+exclude_patterns = [
+    "links.inc",
+    "_build",
+    "naming20.rst",
+    "test/*",
     "old_*",
-    '*attic*',
-    '*/attic*',
-    'funcargs.rst',
-    'setup.rst',
-    'example/remoteinterp.rst',
-    ]
+    "*attic*",
+    "*/attic*",
+    "funcargs.rst",
+    "setup.rst",
+    "example/remoteinterp.rst",
+]
 
 
 # The reST default role (used for this markup: `text`) to use for all documents.
-#default_role = None
+# default_role = None
 
 # If true, '()' will be appended to :func: etc. cross-reference text.
-#add_function_parentheses = True
+# add_function_parentheses = True
 
 # If true, the current module name will be prepended to all description
 # unit titles (such as .. function::).
 add_module_names = False
 
 # If true, sectionauthor and moduleauthor directives will be shown in the
 # output. They are ignored by default.
-#show_authors = False
+# show_authors = False
 
 # The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'sphinx'
-
+pygments_style = "sphinx"
 
 
 # A list of ignored prefixes for module index sorting.
-#modindex_common_prefix = []
+# modindex_common_prefix = []
 
 
 # -- Options for HTML output ---------------------------------------------------
 
-sys.path.append(os.path.abspath('_themes'))
-html_theme_path = ['_themes']
+sys.path.append(os.path.abspath("_themes"))
+html_theme_path = ["_themes"]
 
 # The theme to use for HTML and HTML Help pages.  See the documentation for
 # a list of builtin themes.
-html_theme = 'flask'
+html_theme = "flask"
 
 # Theme options are theme-specific and customize the look and feel of a theme
 # further.  For a list of options available for each theme, see the
 # documentation.
-html_theme_options = {
-  'index_logo': None
-}
+html_theme_options = {"index_logo": None}
 
 # Add any paths that contain custom themes here, relative to this directory.
-#html_theme_path = []
+# html_theme_path = []
 
 # The name for this set of Sphinx documents.  If None, it defaults to
 # "<project> v<release> documentation".
-html_title = 'pytest documentation'
+html_title = "pytest documentation"
 
 # A shorter title for the navigation bar.  Default is the same as html_title.
 html_short_title = "pytest-%s" % release
 
 # The name of an image file (relative to this directory) to place at the top
 # of the sidebar.
 html_logo = "img/pytest1.png"
 
@@ -140,184 +151,193 @@ html_favicon = "img/pytest1favi.ico"
 
 # Add any paths that contain custom static files (such as style sheets) here,
 # relative to this directory. They are copied after the builtin static files,
 # so a file named "default.css" will overwrite the builtin "default.css".
 # html_static_path = ['_static']
 
 # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
 # using the given strftime format.
-#html_last_updated_fmt = '%b %d, %Y'
+# html_last_updated_fmt = '%b %d, %Y'
 
 # If true, SmartyPants will be used to convert quotes and dashes to
 # typographically correct entities.
-#html_use_smartypants = True
+# html_use_smartypants = True
 
 # Custom sidebar templates, maps document names to template names.
-#html_sidebars = {}
-#html_sidebars = {'index': 'indexsidebar.html'}
+# html_sidebars = {}
+# html_sidebars = {'index': 'indexsidebar.html'}
 
 html_sidebars = {
-    'index': [
-        'sidebarintro.html',
-        'globaltoc.html',
-        'links.html',
-        'sourcelink.html',
-        'searchbox.html'
+    "index": [
+        "sidebarintro.html",
+        "globaltoc.html",
+        "links.html",
+        "sourcelink.html",
+        "searchbox.html",
     ],
-    '**': [
-        'globaltoc.html',
-        'relations.html',
-        'links.html',
-        'sourcelink.html',
-        'searchbox.html'
-    ]
+    "**": [
+        "globaltoc.html",
+        "relations.html",
+        "links.html",
+        "sourcelink.html",
+        "searchbox.html",
+    ],
 }
 
 # Additional templates that should be rendered to pages, maps page names to
 # template names.
-#html_additional_pages = {}
-#html_additional_pages = {'index': 'index.html'}
+# html_additional_pages = {}
+# html_additional_pages = {'index': 'index.html'}
 
 
 # If false, no module index is generated.
 html_domain_indices = True
 
 # If false, no index is generated.
 html_use_index = False
 
 # If true, the index is split into individual pages for each letter.
-#html_split_index = False
+# html_split_index = False
 
 # If true, links to the reST sources are added to the pages.
 html_show_sourcelink = False
 
 # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
-#html_show_sphinx = True
+# html_show_sphinx = True
 
 # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
-#html_show_copyright = True
+# html_show_copyright = True
 
 # If true, an OpenSearch description file will be output, and all pages will
 # contain a <link> tag referring to it.  The value of this option must be the
 # base URL from which the finished HTML is served.
-#html_use_opensearch = ''
+# html_use_opensearch = ''
 
 # This is the file name suffix for HTML files (e.g. ".xhtml").
-#html_file_suffix = None
+# html_file_suffix = None
 
 # Output file base name for HTML help builder.
-htmlhelp_basename = 'pytestdoc'
+htmlhelp_basename = "pytestdoc"
 
 
 # -- Options for LaTeX output --------------------------------------------------
 
 # The paper size ('letter' or 'a4').
-#latex_paper_size = 'letter'
+# latex_paper_size = 'letter'
 
 # The font size ('10pt', '11pt' or '12pt').
-#latex_font_size = '10pt'
+# latex_font_size = '10pt'
 
 # Grouping the document tree into LaTeX files. List of tuples
 # (source start file, target name, title, author, documentclass [howto/manual]).
 latex_documents = [
-  ('contents', 'pytest.tex', u'pytest Documentation',
-   u'holger krekel, trainer and consultant, http://merlinux.eu', 'manual'),
+    (
+        "contents",
+        "pytest.tex",
+        u"pytest Documentation",
+        u"holger krekel, trainer and consultant, http://merlinux.eu",
+        "manual",
+    )
 ]
 
 # The name of an image file (relative to this directory) to place at the top of
 # the title page.
-latex_logo = 'img/pytest1.png'
+latex_logo = "img/pytest1.png"
 
 # For "manual" documents, if this is true, then toplevel headings are parts,
 # not chapters.
-#latex_use_parts = False
+# latex_use_parts = False
 
 # If true, show page references after internal links.
-#latex_show_pagerefs = False
+# latex_show_pagerefs = False
 
 # If true, show URL addresses after external links.
-#latex_show_urls = False
+# latex_show_urls = False
 
 # Additional stuff for the LaTeX preamble.
-#latex_preamble = ''
+# latex_preamble = ''
 
 # Documents to append as an appendix to all manuals.
-#latex_appendices = []
+# latex_appendices = []
 
 # If false, no module index is generated.
 latex_domain_indices = False
 
 # -- Options for manual page output --------------------------------------------
 
 # One entry per manual page. List of tuples
 # (source start file, name, description, authors, manual section).
-man_pages = [
-    ('usage', 'pytest', u'pytest usage',
-     [u'holger krekel at merlinux eu'], 1)
-]
+man_pages = [("usage", "pytest", u"pytest usage", [u"holger krekel at merlinux eu"], 1)]
 
 
 # -- Options for Epub output ---------------------------------------------------
 
 # Bibliographic Dublin Core info.
-epub_title = u'pytest'
-epub_author = u'holger krekel at merlinux eu'
-epub_publisher = u'holger krekel at merlinux eu'
-epub_copyright = u'2013, holger krekel et alii'
+epub_title = u"pytest"
+epub_author = u"holger krekel at merlinux eu"
+epub_publisher = u"holger krekel at merlinux eu"
+epub_copyright = u"2013, holger krekel et alii"
 
 # The language of the text. It defaults to the language option
 # or en if the language is not set.
-#epub_language = ''
+# epub_language = ''
 
 # The scheme of the identifier. Typical schemes are ISBN or URL.
-#epub_scheme = ''
+# epub_scheme = ''
 
 # The unique identifier of the text. This can be a ISBN number
 # or the project homepage.
-#epub_identifier = ''
+# epub_identifier = ''
 
 # A unique identification for the text.
-#epub_uid = ''
+# epub_uid = ''
 
 # HTML files that should be inserted before the pages created by sphinx.
 # The format is a list of tuples containing the path and title.
-#epub_pre_files = []
+# epub_pre_files = []
 
 # HTML files shat should be inserted after the pages created by sphinx.
 # The format is a list of tuples containing the path and title.
-#epub_post_files = []
+# epub_post_files = []
 
 # A list of files that should not be packed into the epub file.
-#epub_exclude_files = []
+# epub_exclude_files = []
 
 # The depth of the table of contents in toc.ncx.
-#epub_tocdepth = 3
+# epub_tocdepth = 3
 
 # Allow duplicate toc entries.
-#epub_tocdup = True
+# epub_tocdup = True
 
 
 # -- Options for texinfo output ------------------------------------------------
 
 texinfo_documents = [
-  (master_doc, 'pytest', 'pytest Documentation',
-   ('Holger Krekel@*Benjamin Peterson@*Ronny Pfannschmidt@*'
-    'Floris Bruynooghe@*others'),
-   'pytest',
-   'simple powerful testing with Python',
-   'Programming',
-   1),
+    (
+        master_doc,
+        "pytest",
+        "pytest Documentation",
+        (
+            "Holger Krekel@*Benjamin Peterson@*Ronny Pfannschmidt@*"
+            "Floris Bruynooghe@*others"
+        ),
+        "pytest",
+        "simple powerful testing with Python",
+        "Programming",
+        1,
+    )
 ]
 
 
 # Example configuration for intersphinx: refer to the Python standard library.
-intersphinx_mapping = {'python': ('http://docs.python.org/', None),
-#                       'lib': ("http://docs.python.org/2.7library/", None),
-                    }
+intersphinx_mapping = {"python": ("http://docs.python.org/3", None)}
 
 
 def setup(app):
-    #from sphinx.ext.autodoc import cut_lines
-    #app.connect('autodoc-process-docstring', cut_lines(4, what=['module']))
-    app.add_description_unit('confval', 'confval',
-                             objname='configuration value',
-                             indextemplate='pair: %s; configuration value')
+    # from sphinx.ext.autodoc import cut_lines
+    # app.connect('autodoc-process-docstring', cut_lines(4, what=['module']))
+    app.add_description_unit(
+        "confval",
+        "confval",
+        objname="configuration value",
+        indextemplate="pair: %s; configuration value",
+    )
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/contact.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/contact.rst
@@ -3,19 +3,19 @@
 .. _`contact`:
 
 Contact channels
 ===================================
 
 - `pytest issue tracker`_ to report bugs or suggest features (for version
   2.0 and above).
 
-- `pytest on stackoverflow.com <http://stackoverflow.com/search?q=pytest>`_ 
-  to post questions with the tag ``pytest``.  New Questions will usually 
-  be seen by pytest users or developers and answered quickly. 
+- `pytest on stackoverflow.com <http://stackoverflow.com/search?q=pytest>`_
+  to post questions with the tag ``pytest``.  New Questions will usually
+  be seen by pytest users or developers and answered quickly.
 
 - `Testing In Python`_: a mailing list for Python testing tools and discussion.
 
 - `pytest-dev at python.org (mailing list)`_ pytest specific announcements and discussions.
 
 - `pytest-commit at python.org (mailing list)`_: for commits and new issues
 
 - :doc:`contribution guide <contributing>` for help on submitting pull
@@ -42,9 +42,8 @@ Contact channels
 
 
 .. _`Testing in Python`: http://lists.idyll.org/listinfo/testing-in-python
 .. _FOAF: http://en.wikipedia.org/wiki/FOAF
 .. _`py-dev`:
 .. _`development mailing list`:
 .. _`pytest-dev at python.org (mailing list)`: http://mail.python.org/mailman/listinfo/pytest-dev
 .. _`pytest-commit at python.org (mailing list)`: http://mail.python.org/mailman/listinfo/pytest-commit
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/contents.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/contents.rst
@@ -9,33 +9,33 @@ Full pytest documentation
 
 .. toctree::
    :maxdepth: 2
 
    getting-started
    usage
    existingtestsuite
    assert
-   builtin
    fixture
+   mark
    monkeypatch
    tmpdir
    capture
    warnings
    doctest
-   mark
    skipping
    parametrize
    cache
    unittest
    nose
    xunit_setup
    plugins
    writing_plugins
    logging
+   reference
 
    goodpractices
    pythonpath
    customize
    example/index
    bash-completion
 
    backwards-compatibility
@@ -57,9 +57,8 @@ Full pytest documentation
 
 .. only:: html
 
    .. toctree::
       :hidden:
       :maxdepth: 1
 
       changelog
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/customize.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/customize.rst
@@ -33,16 +33,20 @@ Here's a summary what ``pytest`` uses ``
 
 * Is used by plugins as a stable location to store project/test run specific information;
   for example, the internal :ref:`cache <cache>` plugin creates a ``.cache`` subdirectory
   in ``rootdir`` to store its cross-test run state.
 
 Important to emphasize that ``rootdir`` is **NOT** used to modify ``sys.path``/``PYTHONPATH`` or
 influence how modules are imported. See :ref:`pythonpath` for more details.
 
+``--rootdir=path`` command-line option can be used to force a specific directory.
+The directory passed may contain environment variables when it is used in conjunction
+with ``addopts`` in a ``pytest.ini`` file.
+
 Finding the ``rootdir``
 ~~~~~~~~~~~~~~~~~~~~~~~
 
 Here is the algorithm which finds the rootdir from ``args``:
 
 - determine the common ancestor directory for the specified ``args`` that are
   recognised as paths that exist in the file system. If no such paths are
   found, the common ancestor directory is set to the current working directory.
@@ -147,187 +151,9 @@ The actual command line executed is::
 
 Note that as usual for other command-line applications, in case of conflicting options the last one wins, so the example
 above will show verbose output because ``-v`` overwrites ``-q``.
 
 
 Builtin configuration file options
 ----------------------------------------------
 
-.. confval:: minversion
-
-   Specifies a minimal pytest version required for running tests.
-
-        minversion = 2.1  # will fail if we run with pytest-2.0
-
-.. confval:: addopts
-
-   Add the specified ``OPTS`` to the set of command line arguments as if they
-   had been specified by the user. Example: if you have this ini file content:
-
-   .. code-block:: ini
-
-        [pytest]
-        addopts = --maxfail=2 -rf  # exit after 2 failures, report fail info
-
-   issuing ``pytest test_hello.py`` actually means::
-
-        pytest --maxfail=2 -rf test_hello.py
-
-   Default is to add no options.
-
-.. confval:: norecursedirs
-
-   Set the directory basename patterns to avoid when recursing
-   for test discovery.  The individual (fnmatch-style) patterns are
-   applied to the basename of a directory to decide if to recurse into it.
-   Pattern matching characters::
-
-        *       matches everything
-        ?       matches any single character
-        [seq]   matches any character in seq
-        [!seq]  matches any char not in seq
-
-   Default patterns are ``'.*', 'build', 'dist', 'CVS', '_darcs', '{arch}', '*.egg', 'venv'``.
-   Setting a ``norecursedirs`` replaces the default.  Here is an example of
-   how to avoid certain directories:
-
-   .. code-block:: ini
-
-        # content of pytest.ini
-        [pytest]
-        norecursedirs = .svn _build tmp*
-
-   This would tell ``pytest`` to not look into typical subversion or
-   sphinx-build directories or into any ``tmp`` prefixed directory.  
-   
-   Additionally, ``pytest`` will attempt to intelligently identify and ignore a
-   virtualenv by the presence of an activation script.  Any directory deemed to
-   be the root of a virtual environment will not be considered during test
-   collection unless ``‑‑collect‑in‑virtualenv`` is given.  Note also that
-   ``norecursedirs`` takes precedence over ``‑‑collect‑in‑virtualenv``; e.g. if
-   you intend to run tests in a virtualenv with a base directory that matches
-   ``'.*'`` you *must* override ``norecursedirs`` in addition to using the
-   ``‑‑collect‑in‑virtualenv`` flag.
-
-.. confval:: testpaths
-
-   .. versionadded:: 2.8
-
-   Sets list of directories that should be searched for tests when
-   no specific directories, files or test ids are given in the command line when
-   executing pytest from the :ref:`rootdir <rootdir>` directory.
-   Useful when all project tests are in a known location to speed up
-   test collection and to avoid picking up undesired tests by accident.
-
-   .. code-block:: ini
-
-        # content of pytest.ini
-        [pytest]
-        testpaths = testing doc
-
-   This tells pytest to only look for tests in ``testing`` and ``doc``
-   directories when executing from the root directory.
-
-.. confval:: python_files
-
-   One or more Glob-style file patterns determining which python files
-   are considered as test modules. By default, pytest will consider
-   any file matching with ``test_*.py`` and ``*_test.py`` globs as a test
-   module.
-
-.. confval:: python_classes
-
-   One or more name prefixes or glob-style patterns determining which classes
-   are considered for test collection. By default, pytest will consider any
-   class prefixed with ``Test`` as a test collection.  Here is an example of how
-   to collect tests from classes that end in ``Suite``:
-
-   .. code-block:: ini
-
-        # content of pytest.ini
-        [pytest]
-        python_classes = *Suite
-
-   Note that ``unittest.TestCase`` derived classes are always collected
-   regardless of this option, as ``unittest``'s own collection framework is used
-   to collect those tests.
-
-.. confval:: python_functions
-
-   One or more name prefixes or glob-patterns determining which test functions
-   and methods are considered tests. By default, pytest will consider any
-   function prefixed with ``test`` as a test.  Here is an example of how
-   to collect test functions and methods that end in ``_test``:
-
-   .. code-block:: ini
-
-        # content of pytest.ini
-        [pytest]
-        python_functions = *_test
-
-   Note that this has no effect on methods that live on a ``unittest
-   .TestCase`` derived class, as ``unittest``'s own collection framework is used
-   to collect those tests.
-
-   See :ref:`change naming conventions` for more detailed examples.
-
-.. confval:: doctest_optionflags
-
-   One or more doctest flag names from the standard ``doctest`` module.
-   :doc:`See how pytest handles doctests <doctest>`.
-
-.. confval:: confcutdir
-
-   Sets a directory where search upwards for ``conftest.py`` files stops.
-   By default, pytest will stop searching for ``conftest.py`` files upwards
-   from ``pytest.ini``/``tox.ini``/``setup.cfg`` of the project if any,
-   or up to the file-system root.
-
-
-.. confval:: filterwarnings
-
-   .. versionadded:: 3.1
-
-   Sets a list of filters and actions that should be taken for matched
-   warnings. By default all warnings emitted during the test session
-   will be displayed in a summary at the end of the test session.
-
-   .. code-block:: ini
-
-        # content of pytest.ini
-        [pytest]
-        filterwarnings =
-            error
-            ignore::DeprecationWarning
-
-   This tells pytest to ignore deprecation warnings and turn all other warnings
-   into errors. For more information please refer to :ref:`warnings`.
-
-.. confval:: cache_dir
-
-   .. versionadded:: 3.2
-
-   Sets a directory where stores content of cache plugin. Default directory is
-   ``.cache`` which is created in :ref:`rootdir <rootdir>`. Directory may be
-   relative or absolute path. If setting relative path, then directory is created
-   relative to :ref:`rootdir <rootdir>`. Additionally path may contain environment
-   variables, that will be expanded. For more information about cache plugin
-   please refer to :ref:`cache_provider`.
-
-
-.. confval:: console_output_style
-
-   .. versionadded:: 3.3
-
-   Sets the console output style while running tests:
-
-   * ``classic``: classic pytest output.
-   * ``progress``: like classic pytest output, but with a progress indicator.
-
-   The default is ``progress``, but you can fallback to ``classic`` if you prefer or
-   the new mode is causing unexpected problems:
-
-   .. code-block:: ini
-
-        # content of pytest.ini
-        [pytest]
-        console_output_style = classic
+For the full list of options consult the :ref:`reference documentation <ini options ref>`.
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/development_guide.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/development_guide.rst
@@ -1,21 +1,21 @@
 =================
 Development Guide
 =================
 
-Some general guidelines regarding development in pytest for core maintainers and general contributors. Nothing here
+Some general guidelines regarding development in pytest for maintainers and contributors. Nothing here
 is set in stone and can't be changed, feel free to suggest improvements or changes in the workflow.
 
 
 Code Style
 ----------
 
 * `PEP-8 <https://www.python.org/dev/peps/pep-0008>`_
-* `flake8 <https://pypi.python.org/pypi/flake8>`_ for quality checks
+* `flake8 <https://pypi.org/project/flake8/>`_ for quality checks
 * `invoke <http://www.pyinvoke.org/>`_ to automate development tasks
 
 
 Branches
 --------
 
 We have two long term branches:
 
@@ -32,77 +32,24 @@ topic or where it makes sense to use som
 Issues
 ------
 
 Any question, feature, bug or proposal is welcome as an issue. Users are encouraged to use them whenever they need.
 
 GitHub issues should use labels to categorize them. Labels should be created sporadically, to fill a niche; we should
 avoid creating labels just for the sake of creating them.
 
-Here is a list of labels and a brief description mentioning their intent.
-
-
-**Type**
+Each label should include a description in the GitHub's interface stating its purpose.
 
-* ``type: backward compatibility``: issue that will cause problems with old pytest versions.
-* ``type: bug``: problem that needs to be addressed.
-* ``type: deprecation``: feature that will be deprecated in the future.
-* ``type: docs``: documentation missing or needing clarification.
-* ``type: enhancement``: new feature or API change, should be merged into ``features``.
-* ``type: feature-branch``: new feature or API change, should be merged into ``features``.
-* ``type: infrastructure``: improvement to development/releases/CI structure.
-* ``type: performance``: performance or memory problem/improvement.
-* ``type: proposal``: proposal for a new feature, often to gather opinions or design the API around the new feature.
-* ``type: question``: question regarding usage, installation, internals or how to test something.
-* ``type: refactoring``: internal improvements to the code.
-* ``type: regression``: indicates a problem that was introduced in a release which was working previously.
-
-**Status**
-
-* ``status: critical``: grave problem or usability issue that affects lots of users.
-* ``status: easy``: easy issue that is friendly to new contributors.
-* ``status: help wanted``: core developers need help from experts on this topic.
-* ``status: needs information``: reporter needs to provide more information; can be closed after 2 or more weeks of inactivity.
-
-**Topic**
+Temporary labels
+~~~~~~~~~~~~~~~~
 
-* ``topic: collection``
-* ``topic: fixtures``
-* ``topic: parametrize``
-* ``topic: reporting``
-* ``topic: selection``
-* ``topic: tracebacks``
-
-**Plugin (internal or external)**
+To classify issues for a special event it is encouraged to create a temporary label. This helps those involved to find
+the relevant issues to work on. Examples of that are sprints in Python events or global hacking events.
 
-* ``plugin: cache``
-* ``plugin: capture``
-* ``plugin: doctests``
-* ``plugin: junitxml``
-* ``plugin: monkeypatch``
-* ``plugin: nose``
-* ``plugin: pastebin``
-* ``plugin: pytester``
-* ``plugin: tmpdir``
-* ``plugin: unittest``
-* ``plugin: warnings``
-* ``plugin: xdist``
-
+* ``temporary: EP2017 sprint``: candidate issues or PRs tackled during the EuroPython 2017
 
-**OS**
-
-Issues specific to a single operating system. Do not use as a means to indicate where an issue originated from, only
-for problems that happen **only** in that system.
+Issues created at those events should have other relevant labels added as well.
 
-* ``os: linux``
-* ``os: mac``
-* ``os: windows``
-
-**Temporary**
-
-Used to classify issues for limited time, to help find issues related in events for example.
-They should be removed after they are no longer relevant.
-
-* ``temporary: EP2017 sprint``:
-* ``temporary: sprint-candidate``:
+Those labels should be removed after they are no longer relevant.
 
 
 .. include:: ../../HOWTORELEASE.rst
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/doctest.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/doctest.rst
@@ -60,35 +60,35 @@ and another like this::
 
 then you can just invoke ``pytest`` without command line options::
 
     $ pytest
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini
     collected 1 item
-    
+
     mymodule.py .                                                        [100%]
-    
+
     ========================= 1 passed in 0.12 seconds =========================
 
 It is possible to use fixtures using the ``getfixture`` helper::
 
     # content of example.rst
     >>> tmp = getfixture('tmpdir')
     >>> ...
     >>>
 
 Also, :ref:`usefixtures` and :ref:`autouse` fixtures are supported
 when executing text doctest files.
 
 The standard ``doctest`` module provides some setting flags to configure the
-strictness of doctest tests. In pytest You can enable those flags those flags
-using the configuration file. To make pytest ignore trailing whitespaces and
-ignore lengthy exception stack traces you can just write:
+strictness of doctest tests. In pytest, you can enable those flags using the
+configuration file. To make pytest ignore trailing whitespaces and ignore
+lengthy exception stack traces you can just write:
 
 .. code-block:: ini
 
     [pytest]
     doctest_optionflags= NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL
 
 pytest also introduces new options to allow doctests to run in Python 2 and
 Python 3 unchanged:
@@ -110,16 +110,23 @@ the ``doctest_optionflags`` ini option:
 
 Alternatively, it can be enabled by an inline comment in the doc test
 itself::
 
     # content of example.rst
     >>> get_unicode_greeting()  # doctest: +ALLOW_UNICODE
     'Hello'
 
+By default, pytest would report only the first failure for a given doctest.  If
+you want to continue the test even when you have failures, do::
+
+    pytest --doctest-modules --doctest-continue-on-failure
+
+
+.. _`doctest_namespace`:
 
 The 'doctest_namespace' fixture
 -------------------------------
 
 .. versionadded:: 3.0
 
 The ``doctest_namespace`` fixture can be used to inject items into the
 namespace in which your doctests run. It is intended to be used within
@@ -156,10 +163,8 @@ by using one of standard doctest modules
 (see :data:`python:doctest.REPORT_UDIFF`, :data:`python:doctest.REPORT_CDIFF`,
 :data:`python:doctest.REPORT_NDIFF`, :data:`python:doctest.REPORT_ONLY_FIRST_FAILURE`)::
 
     pytest --doctest-modules --doctest-report none
     pytest --doctest-modules --doctest-report udiff
     pytest --doctest-modules --doctest-report cdiff
     pytest --doctest-modules --doctest-report ndiff
     pytest --doctest-modules --doctest-report only_first_failure
-
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/failure_demo.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/failure_demo.py
@@ -1,238 +1,278 @@
 from pytest import raises
 import _pytest._code
 import py
 
-def otherfunc(a,b):
-    assert a==b
+
+def otherfunc(a, b):
+    assert a == b
+
 
-def somefunc(x,y):
-    otherfunc(x,y)
+def somefunc(x, y):
+    otherfunc(x, y)
+
 
-def otherfunc_multi(a,b):
-    assert (a ==
-            b)
+def otherfunc_multi(a, b):
+    assert a == b
+
 
 def test_generative(param1, param2):
     assert param1 * 2 < param2
 
+
 def pytest_generate_tests(metafunc):
-    if 'param1' in metafunc.fixturenames:
+    if "param1" in metafunc.fixturenames:
         metafunc.addcall(funcargs=dict(param1=3, param2=6))
 
+
 class TestFailing(object):
+
     def test_simple(self):
+
         def f():
             return 42
+
         def g():
             return 43
 
         assert f() == g()
 
     def test_simple_multiline(self):
-        otherfunc_multi(
-                  42,
-                  6*9)
+        otherfunc_multi(42, 6 * 9)
 
     def test_not(self):
+
         def f():
             return 42
+
         assert not f()
 
+
 class TestSpecialisedExplanations(object):
+
     def test_eq_text(self):
-        assert 'spam' == 'eggs'
+        assert "spam" == "eggs"
 
     def test_eq_similar_text(self):
-        assert 'foo 1 bar' == 'foo 2 bar'
+        assert "foo 1 bar" == "foo 2 bar"
 
     def test_eq_multiline_text(self):
-        assert 'foo\nspam\nbar' == 'foo\neggs\nbar'
+        assert "foo\nspam\nbar" == "foo\neggs\nbar"
 
     def test_eq_long_text(self):
-        a = '1'*100 + 'a' + '2'*100
-        b = '1'*100 + 'b' + '2'*100
+        a = "1" * 100 + "a" + "2" * 100
+        b = "1" * 100 + "b" + "2" * 100
         assert a == b
 
     def test_eq_long_text_multiline(self):
-        a = '1\n'*100 + 'a' + '2\n'*100
-        b = '1\n'*100 + 'b' + '2\n'*100
+        a = "1\n" * 100 + "a" + "2\n" * 100
+        b = "1\n" * 100 + "b" + "2\n" * 100
         assert a == b
 
     def test_eq_list(self):
         assert [0, 1, 2] == [0, 1, 3]
 
     def test_eq_list_long(self):
-        a = [0]*100 + [1] + [3]*100
-        b = [0]*100 + [2] + [3]*100
+        a = [0] * 100 + [1] + [3] * 100
+        b = [0] * 100 + [2] + [3] * 100
         assert a == b
 
     def test_eq_dict(self):
-        assert {'a': 0, 'b': 1, 'c': 0} == {'a': 0, 'b': 2, 'd': 0}
+        assert {"a": 0, "b": 1, "c": 0} == {"a": 0, "b": 2, "d": 0}
 
     def test_eq_set(self):
-        assert set([0, 10, 11, 12]) == set([0, 20, 21])
+        assert {0, 10, 11, 12} == {0, 20, 21}
 
     def test_eq_longer_list(self):
-        assert [1,2] == [1,2,3]
+        assert [1, 2] == [1, 2, 3]
 
     def test_in_list(self):
         assert 1 in [0, 2, 3, 4, 5]
 
     def test_not_in_text_multiline(self):
-        text = 'some multiline\ntext\nwhich\nincludes foo\nand a\ntail'
-        assert 'foo' not in text
+        text = "some multiline\ntext\nwhich\nincludes foo\nand a\ntail"
+        assert "foo" not in text
 
     def test_not_in_text_single(self):
-        text = 'single foo line'
-        assert 'foo' not in text
+        text = "single foo line"
+        assert "foo" not in text
 
     def test_not_in_text_single_long(self):
-        text = 'head ' * 50 + 'foo ' + 'tail ' * 20
-        assert 'foo' not in text
+        text = "head " * 50 + "foo " + "tail " * 20
+        assert "foo" not in text
 
     def test_not_in_text_single_long_term(self):
-        text = 'head ' * 50 + 'f'*70 + 'tail ' * 20
-        assert 'f'*70 not in text
+        text = "head " * 50 + "f" * 70 + "tail " * 20
+        assert "f" * 70 not in text
 
 
 def test_attribute():
+
     class Foo(object):
         b = 1
+
     i = Foo()
     assert i.b == 2
 
 
 def test_attribute_instance():
+
     class Foo(object):
         b = 1
+
     assert Foo().b == 2
 
 
 def test_attribute_failure():
+
     class Foo(object):
+
         def _get_b(self):
-            raise Exception('Failed to get attrib')
+            raise Exception("Failed to get attrib")
+
         b = property(_get_b)
+
     i = Foo()
     assert i.b == 2
 
 
 def test_attribute_multiple():
+
     class Foo(object):
         b = 1
+
     class Bar(object):
         b = 2
+
     assert Foo().b == Bar().b
 
 
 def globf(x):
-    return x+1
+    return x + 1
+
 
 class TestRaises(object):
+
     def test_raises(self):
-        s = 'qwe'
+        s = "qwe"  # NOQA
         raises(TypeError, "int(s)")
 
     def test_raises_doesnt(self):
         raises(IOError, "int('3')")
 
     def test_raise(self):
         raise ValueError("demo error")
 
     def test_tupleerror(self):
-        a,b = [1]
+        a, b = [1]  # NOQA
 
     def test_reinterpret_fails_with_print_for_the_fun_of_it(self):
-        l = [1,2,3]
-        print ("l is %r" % l)
-        a,b = l.pop()
+        items = [1, 2, 3]
+        print("items is %r" % items)
+        a, b = items.pop()
 
     def test_some_error(self):
-        if namenotexi:
+        if namenotexi:  # NOQA
             pass
 
     def func1(self):
         assert 41 == 42
 
 
 # thanks to Matthew Scott for this test
 def test_dynamic_compile_shows_nicely():
-    src = 'def foo():\n assert 1 == 0\n'
-    name = 'abc-123'
-    module = py.std.imp.new_module(name)
-    code = _pytest._code.compile(src, name, 'exec')
+    import imp
+    import sys
+
+    src = "def foo():\n assert 1 == 0\n"
+    name = "abc-123"
+    module = imp.new_module(name)
+    code = _pytest._code.compile(src, name, "exec")
     py.builtin.exec_(code, module.__dict__)
-    py.std.sys.modules[name] = module
+    sys.modules[name] = module
     module.foo()
 
 
-
 class TestMoreErrors(object):
+
     def test_complex_error(self):
+
         def f():
             return 44
+
         def g():
             return 43
+
         somefunc(f(), g())
 
     def test_z1_unpack_error(self):
-        l = []
-        a,b  = l
+        items = []
+        a, b = items
 
     def test_z2_type_error(self):
-        l = 3
-        a,b  = l
+        items = 3
+        a, b = items
 
     def test_startswith(self):
         s = "123"
         g = "456"
         assert s.startswith(g)
 
     def test_startswith_nested(self):
+
         def f():
             return "123"
+
         def g():
             return "456"
+
         assert f().startswith(g())
 
     def test_global_func(self):
         assert isinstance(globf(42), float)
 
     def test_instance(self):
-        self.x = 6*7
+        self.x = 6 * 7
         assert self.x != 42
 
     def test_compare(self):
         assert globf(10) < 5
 
     def test_try_finally(self):
         x = 1
         try:
             assert x == 0
         finally:
             x = 0
 
 
 class TestCustomAssertMsg(object):
 
     def test_single_line(self):
+
         class A(object):
             a = 1
+
         b = 2
         assert A.a == b, "A.a appears not to be b"
 
     def test_multiline(self):
+
         class A(object):
             a = 1
+
         b = 2
-        assert A.a == b, "A.a appears not to be b\n" \
-            "or does not appear to be b\none of those"
+        assert (
+            A.a == b
+        ), "A.a appears not to be b\n" "or does not appear to be b\none of those"
 
     def test_custom_repr(self):
+
         class JSON(object):
             a = 1
+
             def __repr__(self):
                 return "This is JSON\n{\n  'foo': 'bar'\n}"
+
         a = JSON()
         b = 2
         assert a.a == b, a
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/global_testmodule_config/conftest.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/global_testmodule_config/conftest.py
@@ -1,10 +1,13 @@
-import pytest, py
+import pytest
+import py
+
 mydir = py.path.local(__file__).dirpath()
 
+
 def pytest_runtest_setup(item):
     if isinstance(item, pytest.Function):
         if not item.fspath.relto(mydir):
             return
         mod = item.getparent(pytest.Module).obj
-        if hasattr(mod, 'hello'):
-            print ("mod.hello %r" % (mod.hello,))
+        if hasattr(mod, "hello"):
+            print("mod.hello %r" % (mod.hello,))
rename from testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/global_testmodule_config/test_hello.py
rename to testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/global_testmodule_config/test_hello_world.py
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/test_failures.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/test_failures.py
@@ -1,14 +1,14 @@
 
 import py
-failure_demo = py.path.local(__file__).dirpath('failure_demo.py')
-pytest_plugins = 'pytester',
+
+failure_demo = py.path.local(__file__).dirpath("failure_demo.py")
+pytest_plugins = "pytester",
+
 
 def test_failure_demo_fails_properly(testdir):
     target = testdir.tmpdir.join(failure_demo.basename)
     failure_demo.copy(target)
     failure_demo.copy(testdir.tmpdir.join(failure_demo.basename))
     result = testdir.runpytest(target, syspathinsert=True)
-    result.stdout.fnmatch_lines([
-        "*42 failed*"
-    ])
+    result.stdout.fnmatch_lines(["*42 failed*"])
     assert result.ret != 0
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/test_setup_flow_example.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/assertion/test_setup_flow_example.py
@@ -1,12 +1,14 @@
 def setup_module(module):
     module.TestStateFullThing.classcount = 0
 
+
 class TestStateFullThing(object):
+
     def setup_class(cls):
         cls.classcount += 1
 
     def teardown_class(cls):
         cls.classcount -= 1
 
     def setup_method(self, method):
         self.id = eval(method.__name__[5:])
@@ -14,19 +16,21 @@ class TestStateFullThing(object):
     def test_42(self):
         assert self.classcount == 1
         assert self.id == 42
 
     def test_23(self):
         assert self.classcount == 1
         assert self.id == 23
 
+
 def teardown_module(module):
     assert module.TestStateFullThing.classcount == 0
 
+
 """ For this example the control flow happens as follows::
     import test_setup_flow_example
     setup_module(test_setup_flow_example)
        setup_class(TestStateFullThing)
            instance = TestStateFullThing()
            setup_method(instance, instance.test_42)
               instance.test_42()
            setup_method(instance, instance.test_23)
@@ -34,9 +38,8 @@ def teardown_module(module):
        teardown_class(TestStateFullThing)
     teardown_module(test_setup_flow_example)
 
 Note that ``setup_class(TestStateFullThing)`` is called and not
 ``TestStateFullThing.setup_class()`` which would require you
 to insert ``setup_class = classmethod(setup_class)`` to make
 your setup function callable.
 """
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/attic.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/attic.rst
@@ -4,25 +4,28 @@
 example: specifying and selecting acceptance tests
 --------------------------------------------------------------
 
 .. sourcecode:: python
 
     # ./conftest.py
     def pytest_option(parser):
         group = parser.getgroup("myproject")
-        group.addoption("-A", dest="acceptance", action="store_true",
-            help="run (slow) acceptance tests")
+        group.addoption(
+            "-A", dest="acceptance", action="store_true", help="run (slow) acceptance tests"
+        )
+
 
     def pytest_funcarg__accept(request):
         return AcceptFixture(request)
 
+
     class AcceptFixture(object):
         def __init__(self, request):
-            if not request.config.getoption('acceptance'):
+            if not request.config.getoption("acceptance"):
                 pytest.skip("specify -A to run acceptance tests")
             self.tmpdir = request.config.mktemp(request.function.__name__, numbered=True)
 
         def run(self, cmd):
             """ called by test code to execute an acceptance test. """
             self.tmpdir.chdir()
             return py.process.cmdexec(cmd)
 
@@ -56,16 +59,17 @@ extend the `accept example`_ by putting 
 
     def pytest_funcarg__accept(request):
         # call the next factory (living in our conftest.py)
         arg = request.getfuncargvalue("accept")
         # create a special layout in our tempdir
         arg.tmpdir.mkdir("special")
         return arg
 
+
     class TestSpecialAcceptance(object):
         def test_sometest(self, accept):
             assert accept.tmpdir.join("special").check()
 
 Our module level factory will be invoked first and it can
 ask its request object to call the next factory and then
 decorate its result.  This mechanism allows us to stay
 ignorant of how/where the function argument is provided -
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/conftest.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/conftest.py
@@ -1,18 +1,22 @@
 
 import pytest
 
+
 @pytest.fixture("session")
 def setup(request):
     setup = CostlySetup()
     yield setup
     setup.finalize()
 
+
 class CostlySetup(object):
+
     def __init__(self):
         import time
-        print ("performing costly setup")
+
+        print("performing costly setup")
         time.sleep(5)
         self.timecostly = 1
 
     def finalize(self):
         del self.timecostly
rename from testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub1/__init__.py
rename to testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub_a/__init__.py
rename from testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub1/test_quick.py
rename to testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub_a/test_quick.py
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub1/test_quick.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub_a/test_quick.py
@@ -1,3 +1,2 @@
-
 def test_quick(setup):
     pass
rename from testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub2/__init__.py
rename to testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub_b/__init__.py
rename from testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub2/test_two.py
rename to testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub_b/test_two.py
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub2/test_two.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/costlysetup/sub_b/test_two.py
@@ -1,6 +1,6 @@
 def test_something(setup):
     assert setup.timecostly == 1
 
+
 def test_something_more(setup):
     assert setup.timecostly == 1
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/markers.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/markers.rst
@@ -27,84 +27,82 @@ You can "mark" a test function with cust
 
 .. versionadded:: 2.2
 
 You can then restrict a test run to only run tests marked with ``webtest``::
 
     $ pytest -v -m webtest
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
-    cachedir: .cache
+    cachedir: .pytest_cache
     rootdir: $REGENDOC_TMPDIR, inifile:
-    collecting ... collected 4 items
-    
+    collecting ... collected 4 items / 3 deselected
+
     test_server.py::test_send_http PASSED                                [100%]
-    
-    ============================ 3 tests deselected ============================
+
     ================== 1 passed, 3 deselected in 0.12 seconds ==================
 
 Or the inverse, running all tests except the webtest ones::
 
     $ pytest -v -m "not webtest"
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
-    cachedir: .cache
+    cachedir: .pytest_cache
     rootdir: $REGENDOC_TMPDIR, inifile:
-    collecting ... collected 4 items
-    
+    collecting ... collected 4 items / 1 deselected
+
     test_server.py::test_something_quick PASSED                          [ 33%]
     test_server.py::test_another PASSED                                  [ 66%]
     test_server.py::TestClass::test_method PASSED                        [100%]
-    
-    ============================ 1 tests deselected ============================
+
     ================== 3 passed, 1 deselected in 0.12 seconds ==================
 
 Selecting tests based on their node ID
 --------------------------------------
 
 You can provide one or more :ref:`node IDs <node-id>` as positional
 arguments to select only specified tests. This makes it easy to select
 tests based on their module, class, method, or function name::
 
     $ pytest -v test_server.py::TestClass::test_method
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
-    cachedir: .cache
+    cachedir: .pytest_cache
     rootdir: $REGENDOC_TMPDIR, inifile:
     collecting ... collected 1 item
-    
+
     test_server.py::TestClass::test_method PASSED                        [100%]
-    
+
     ========================= 1 passed in 0.12 seconds =========================
 
 You can also select on the class::
 
     $ pytest -v test_server.py::TestClass
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
-    cachedir: .cache
+    cachedir: .pytest_cache
     rootdir: $REGENDOC_TMPDIR, inifile:
     collecting ... collected 1 item
-    
+
     test_server.py::TestClass::test_method PASSED                        [100%]
-    
+
     ========================= 1 passed in 0.12 seconds =========================
 
 Or select multiple nodes::
 
   $ pytest -v test_server.py::TestClass test_server.py::test_send_http
   =========================== test session starts ============================
   platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
-  cachedir: .cache
+  cachedir: .pytest_cache
   rootdir: $REGENDOC_TMPDIR, inifile:
   collecting ... collected 2 items
-  
+
   test_server.py::TestClass::test_method PASSED                        [ 50%]
   test_server.py::test_send_http PASSED                                [100%]
-  
+
   ========================= 2 passed in 0.12 seconds =========================
 
 .. _node-id:
 
 .. note::
 
     Node IDs are of the form ``module.py::class::method`` or
     ``module.py::function``.  Node IDs control which tests are
@@ -126,54 +124,51 @@ Using ``-k expr`` to select tests based 
 You can use the ``-k`` command line option to specify an expression
 which implements a substring match on the test names instead of the
 exact match on markers that ``-m`` provides.  This makes it easy to
 select tests based on their names::
 
     $ pytest -v -k http  # running with the above defined example module
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
-    cachedir: .cache
+    cachedir: .pytest_cache
     rootdir: $REGENDOC_TMPDIR, inifile:
-    collecting ... collected 4 items
-    
+    collecting ... collected 4 items / 3 deselected
+
     test_server.py::test_send_http PASSED                                [100%]
-    
-    ============================ 3 tests deselected ============================
+
     ================== 1 passed, 3 deselected in 0.12 seconds ==================
 
 And you can also run all tests except the ones that match the keyword::
 
     $ pytest -k "not send_http" -v
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
-    cachedir: .cache
+    cachedir: .pytest_cache
     rootdir: $REGENDOC_TMPDIR, inifile:
-    collecting ... collected 4 items
-    
+    collecting ... collected 4 items / 1 deselected
+
     test_server.py::test_something_quick PASSED                          [ 33%]
     test_server.py::test_another PASSED                                  [ 66%]
     test_server.py::TestClass::test_method PASSED                        [100%]
-    
-    ============================ 1 tests deselected ============================
+
     ================== 3 passed, 1 deselected in 0.12 seconds ==================
 
 Or to select "http" and "quick" tests::
 
     $ pytest -k "http or quick" -v
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
-    cachedir: .cache
+    cachedir: .pytest_cache
     rootdir: $REGENDOC_TMPDIR, inifile:
-    collecting ... collected 4 items
-    
+    collecting ... collected 4 items / 2 deselected
+
     test_server.py::test_send_http PASSED                                [ 50%]
     test_server.py::test_something_quick PASSED                          [100%]
-    
-    ============================ 2 tests deselected ============================
+
     ================== 2 passed, 2 deselected in 0.12 seconds ==================
 
 .. note::
 
     If you are using expressions such as ``"X and Y"`` then both ``X`` and ``Y``
     need to be simple non-keyword names. For example, ``"pass"`` or ``"from"``
     will result in SyntaxErrors because ``"-k"`` evaluates the expression using
     Python's `eval`_ function.
@@ -199,45 +194,45 @@ Registering markers for your test suite 
     [pytest]
     markers =
         webtest: mark a test as a webtest.
 
 You can ask which markers exist for your test suite - the list includes our just defined ``webtest`` markers::
 
     $ pytest --markers
     @pytest.mark.webtest: mark a test as a webtest.
-    
+
     @pytest.mark.skip(reason=None): skip the given test function with an optional reason. Example: skip(reason="no way of currently testing this") skips the test.
-    
+
     @pytest.mark.skipif(condition): skip the given test function if eval(condition) results in a True value.  Evaluation happens within the module global context. Example: skipif('sys.platform == "win32"') skips the test if we are on the win32 platform. see http://pytest.org/latest/skipping.html
-    
+
     @pytest.mark.xfail(condition, reason=None, run=True, raises=None, strict=False): mark 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
-    
+
     @pytest.mark.parametrize(argnames, argvalues): call a test function multiple times passing in different arguments in turn. argvalues generally needs to be a list of values if argnames specifies only one name or a list of tuples of values if argnames specifies multiple names. Example: @parametrize('arg1', [1,2]) would lead to two calls of the decorated test function, one with arg1=1 and another with arg1=2.see http://pytest.org/latest/parametrize.html for more info and examples.
-    
-    @pytest.mark.usefixtures(fixturename1, fixturename2, ...): mark tests as needing all of the specified fixtures. see http://pytest.org/latest/fixture.html#usefixtures 
-    
+
+    @pytest.mark.usefixtures(fixturename1, fixturename2, ...): mark tests as needing all of the specified fixtures. see http://pytest.org/latest/fixture.html#usefixtures
+
     @pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to call it first/as early as possible.
-    
+
     @pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to call it last/as late as possible.
-    
+
 
 For an example on how to add and work with markers from a plugin, see
 :ref:`adding a custom marker from a plugin`.
 
 .. note::
 
     It is recommended to explicitly register markers so that:
 
     * There is one place in your test suite defining your markers
 
     * Asking for existing markers via ``pytest --markers`` gives good output
 
     * Typos in function markers are treated as an error if you use
-      the ``--strict`` option. 
+      the ``--strict`` option.
 
 .. _`scoped-marking`:
 
 Marking whole classes or modules
 ----------------------------------------------------
 
 You may use ``pytest.mark`` decorators with classes to apply markers to all of
 its test methods::
@@ -330,21 +325,20 @@ specifies via named environments::
             help="only run tests matching the environment NAME.")
 
     def pytest_configure(config):
         # register an additional marker
         config.addinivalue_line("markers",
             "env(name): mark test to run only on named environment")
 
     def pytest_runtest_setup(item):
-        envmarker = item.get_marker("env")
-        if envmarker is not None:
-            envname = envmarker.args[0]
-            if envname != item.config.getoption("-E"):
-                pytest.skip("test requires env %r" % envname)
+        envnames = [mark.args[0] for mark in item.iter_markers(name='env')]
+        if envnames:
+            if item.config.getoption("-E") not in envnames:
+                pytest.skip("test requires env in %r" % envnames)
 
 A test file using this local plugin::
 
     # content of test_someenv.py
 
     import pytest
     @pytest.mark.env("stage1")
     def test_basic_db_operation():
@@ -353,71 +347,69 @@ A test file using this local plugin::
 and an example invocations specifying a different environment than what
 the test needs::
 
     $ pytest -E stage2
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 1 item
-    
+
     test_someenv.py s                                                    [100%]
-    
+
     ======================== 1 skipped in 0.12 seconds =========================
 
 and here is one that specifies exactly the environment needed::
 
     $ pytest -E stage1
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 1 item
-    
+
     test_someenv.py .                                                    [100%]
-    
+
     ========================= 1 passed in 0.12 seconds =========================
 
 The ``--markers`` option always gives you a list of available markers::
 
     $ pytest --markers
     @pytest.mark.env(name): mark test to run only on named environment
-    
+
     @pytest.mark.skip(reason=None): skip the given test function with an optional reason. Example: skip(reason="no way of currently testing this") skips the test.
-    
+
     @pytest.mark.skipif(condition): skip the given test function if eval(condition) results in a True value.  Evaluation happens within the module global context. Example: skipif('sys.platform == "win32"') skips the test if we are on the win32 platform. see http://pytest.org/latest/skipping.html
-    
+
     @pytest.mark.xfail(condition, reason=None, run=True, raises=None, strict=False): mark 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
-    
+
     @pytest.mark.parametrize(argnames, argvalues): call a test function multiple times passing in different arguments in turn. argvalues generally needs to be a list of values if argnames specifies only one name or a list of tuples of values if argnames specifies multiple names. Example: @parametrize('arg1', [1,2]) would lead to two calls of the decorated test function, one with arg1=1 and another with arg1=2.see http://pytest.org/latest/parametrize.html for more info and examples.
-    
-    @pytest.mark.usefixtures(fixturename1, fixturename2, ...): mark tests as needing all of the specified fixtures. see http://pytest.org/latest/fixture.html#usefixtures 
-    
+
+    @pytest.mark.usefixtures(fixturename1, fixturename2, ...): mark tests as needing all of the specified fixtures. see http://pytest.org/latest/fixture.html#usefixtures
+
     @pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to call it first/as early as possible.
-    
+
     @pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to call it last/as late as possible.
-    
+
 
 .. _`passing callables to custom markers`:
 
 Passing a callable to custom markers
 --------------------------------------------
 
 .. regendoc:wipe
 
 Below is the config file that will be used in the next examples::
 
     # content of conftest.py
     import sys
 
     def pytest_runtest_setup(item):
-        marker = item.get_marker('my_marker')
-        if marker is not None:
-            for info in marker:
-                print('Marker info name={} args={} kwars={}'.format(info.name, info.args, info.kwargs))
-                sys.stdout.flush()
+        for marker in item.iter_markers(name='my_marker'):
+            print(marker)
+            sys.stdout.flush()
 
 A custom marker can have its argument set, i.e. ``args`` and ``kwargs`` properties, defined by either invoking it as a callable or using ``pytest.mark.MARKER_NAME.with_args``. These two methods achieve the same effect most of the time.
 
 However, if there is a callable as the single positional argument with no keyword arguments, using the ``pytest.mark.MARKER_NAME(c)`` will not pass ``c`` as a positional argument but decorate ``c`` with the custom marker (see :ref:`MarkDecorator <mark>`). Fortunately, ``pytest.mark.MARKER_NAME.with_args`` comes to the rescue::
 
     # content of test_custom_marker.py
     import pytest
 
@@ -426,18 +418,18 @@ However, if there is a callable as the s
 
     @pytest.mark.my_marker.with_args(hello_world)
     def test_with_args():
         pass
 
 The output is as follows::
 
     $ pytest -q -s
-    Marker info name=my_marker args=(<function hello_world at 0xdeadbeef>,) kwars={}
-    .                                                                    [100%]
+    Mark(name='my_marker', args=(<function hello_world at 0xdeadbeef>,), kwargs={})
+    .
     1 passed in 0.12 seconds
 
 We can see that the custom marker has its argument set extended with the function ``hello_world``. This is the key difference between creating a custom marker as a callable, which invokes ``__call__`` behind the scenes, and using ``with_args``.
 
 
 Reading markers which were set from multiple places
 ----------------------------------------------------
 
@@ -460,29 +452,27 @@ code you can read over all such settings
 
 Here we have the marker "glob" applied three times to the same
 test function.  From a conftest file we can read it like this::
 
     # content of conftest.py
     import sys
 
     def pytest_runtest_setup(item):
-        g = item.get_marker("glob")
-        if g is not None:
-            for info in g:
-                print ("glob args=%s kwargs=%s" %(info.args, info.kwargs))
-                sys.stdout.flush()
+        for mark in item.iter_markers(name='glob'):
+            print ("glob args=%s kwargs=%s" %(mark.args, mark.kwargs))
+            sys.stdout.flush()
 
 Let's run this without capturing output and see what we get::
 
     $ pytest -q -s
     glob args=('function',) kwargs={'x': 3}
     glob args=('class',) kwargs={'x': 2}
     glob args=('module',) kwargs={'x': 1}
-    .                                                                    [100%]
+    .
     1 passed in 0.12 seconds
 
 marking platform specific tests with pytest
 --------------------------------------------------------------
 
 .. regendoc:wipe
 
 Consider you have a test suite which marks tests for particular platforms,
@@ -494,21 +484,20 @@ for your particular platform, you could 
     # content of conftest.py
     #
     import sys
     import pytest
 
     ALL = set("darwin linux win32".split())
 
     def pytest_runtest_setup(item):
-        if isinstance(item, item.Function):
-            plat = sys.platform
-            if not item.get_marker(plat):
-                if ALL.intersection(item.keywords):
-                    pytest.skip("cannot run on platform %s" %(plat))
+        supported_platforms = ALL.intersection(mark.name for mark in item.iter_markers())
+        plat = sys.platform
+        if supported_platforms and plat not in supported_platforms:
+            pytest.skip("cannot run on platform %s" % (plat))
 
 then tests will be skipped if they were specified for a different platform.
 Let's do a little test file to show how this looks like::
 
     # content of test_plat.py
 
     import pytest
 
@@ -529,34 +518,33 @@ Let's do a little test file to show how 
 
 then you will see two tests skipped and two executed tests as expected::
 
     $ pytest -rs # this option reports skip reasons
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 4 items
-    
+
     test_plat.py s.s.                                                    [100%]
     ========================= short test summary info ==========================
-    SKIP [2] $REGENDOC_TMPDIR/conftest.py:13: cannot run on platform linux
-    
+    SKIP [2] $REGENDOC_TMPDIR/conftest.py:12: cannot run on platform linux
+
     =================== 2 passed, 2 skipped in 0.12 seconds ====================
 
 Note that if you specify a platform via the marker-command line option like this::
 
     $ pytest -m linux
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
-    collected 4 items
-    
+    collected 4 items / 3 deselected
+
     test_plat.py .                                                       [100%]
-    
-    ============================ 3 tests deselected ============================
+
     ================== 1 passed, 3 deselected in 0.12 seconds ==================
 
 then the unmarked-tests will not be run.  It is thus a way to restrict the run to the specific tests.
 
 Automatically adding markers based on test names
 --------------------------------------------------------
 
 .. regendoc:wipe
@@ -594,49 +582,47 @@ We want to dynamically define two marker
                 item.add_marker(pytest.mark.event)
 
 We can now use the ``-m option`` to select one set::
 
   $ pytest -m interface --tb=short
   =========================== test session starts ============================
   platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
   rootdir: $REGENDOC_TMPDIR, inifile:
-  collected 4 items
-  
+  collected 4 items / 2 deselected
+
   test_module.py FF                                                    [100%]
-  
+
   ================================= FAILURES =================================
   __________________________ test_interface_simple ___________________________
   test_module.py:3: in test_interface_simple
       assert 0
   E   assert 0
   __________________________ test_interface_complex __________________________
   test_module.py:6: in test_interface_complex
       assert 0
   E   assert 0
-  ============================ 2 tests deselected ============================
   ================== 2 failed, 2 deselected in 0.12 seconds ==================
 
 or to select both "event" and "interface" tests::
 
   $ pytest -m "interface or event" --tb=short
   =========================== test session starts ============================
   platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
   rootdir: $REGENDOC_TMPDIR, inifile:
-  collected 4 items
-  
+  collected 4 items / 1 deselected
+
   test_module.py FFF                                                   [100%]
-  
+
   ================================= FAILURES =================================
   __________________________ test_interface_simple ___________________________
   test_module.py:3: in test_interface_simple
       assert 0
   E   assert 0
   __________________________ test_interface_complex __________________________
   test_module.py:6: in test_interface_complex
       assert 0
   E   assert 0
   ____________________________ test_event_simple _____________________________
   test_module.py:9: in test_event_simple
       assert 0
   E   assert 0
-  ============================ 1 tests deselected ============================
   ================== 3 failed, 1 deselected in 0.12 seconds ==================
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/multipython.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/multipython.py
@@ -1,52 +1,69 @@
 """
 module containing a parametrized tests testing cross-python
 serialization via the pickle module.
 """
 import py
 import pytest
 import _pytest._code
 
-pythonlist = ['python2.7', 'python3.4', 'python3.5']
+pythonlist = ["python2.7", "python3.4", "python3.5"]
+
+
 @pytest.fixture(params=pythonlist)
 def python1(request, tmpdir):
     picklefile = tmpdir.join("data.pickle")
     return Python(request.param, picklefile)
 
+
 @pytest.fixture(params=pythonlist)
 def python2(request, python1):
     return Python(request.param, python1.picklefile)
 
+
 class Python(object):
+
     def __init__(self, version, picklefile):
         self.pythonpath = py.path.local.sysfind(version)
         if not self.pythonpath:
-            pytest.skip("%r not found" %(version,))
+            pytest.skip("%r not found" % (version,))
         self.picklefile = picklefile
+
     def dumps(self, obj):
         dumpfile = self.picklefile.dirpath("dump.py")
-        dumpfile.write(_pytest._code.Source("""
+        dumpfile.write(
+            _pytest._code.Source(
+                """
             import pickle
             f = open(%r, 'wb')
             s = pickle.dump(%r, f, protocol=2)
             f.close()
-        """ % (str(self.picklefile), obj)))
-        py.process.cmdexec("%s %s" %(self.pythonpath, dumpfile))
+        """
+                % (str(self.picklefile), obj)
+            )
+        )
+        py.process.cmdexec("%s %s" % (self.pythonpath, dumpfile))
 
     def load_and_is_true(self, expression):
         loadfile = self.picklefile.dirpath("load.py")
-        loadfile.write(_pytest._code.Source("""
+        loadfile.write(
+            _pytest._code.Source(
+                """
             import pickle
             f = open(%r, 'rb')
             obj = pickle.load(f)
             f.close()
             res = eval(%r)
             if not res:
                 raise SystemExit(1)
-        """ % (str(self.picklefile), expression)))
-        print (loadfile)
-        py.process.cmdexec("%s %s" %(self.pythonpath, loadfile))
+        """
+                % (str(self.picklefile), expression)
+            )
+        )
+        print(loadfile)
+        py.process.cmdexec("%s %s" % (self.pythonpath, loadfile))
 
-@pytest.mark.parametrize("obj", [42, {}, {1:3},])
+
+@pytest.mark.parametrize("obj", [42, {}, {1: 3}])
 def test_basic_objects(python1, python2, obj):
     python1.dumps(obj)
     python2.load_and_is_true("obj == %s" % obj)
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/nonpython.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/nonpython.rst
@@ -5,17 +5,17 @@ Working with non-python tests
 ====================================================
 
 .. _`yaml plugin`:
 
 A basic example for specifying tests in Yaml files
 --------------------------------------------------------------
 
 .. _`pytest-yamlwsgi`: http://bitbucket.org/aafshar/pytest-yamlwsgi/src/tip/pytest_yamlwsgi.py
-.. _`PyYAML`: http://pypi.python.org/pypi/PyYAML/
+.. _`PyYAML`: https://pypi.org/project/PyYAML/
 
 Here is an example ``conftest.py`` (extracted from Ali Afshnars special purpose `pytest-yamlwsgi`_ plugin).   This ``conftest.py`` will  collect ``test*.yml`` files and will execute the yaml-formatted content as custom tests:
 
 .. include:: nonpython/conftest.py
     :literal:
 
 You can create a simple example file:
 
@@ -25,19 +25,19 @@ You can create a simple example file:
 and if you installed `PyYAML`_ or a compatible YAML-parser you can
 now execute the test specification::
 
     nonpython $ pytest test_simple.yml
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR/nonpython, inifile:
     collected 2 items
-    
+
     test_simple.yml F.                                                   [100%]
-    
+
     ================================= FAILURES =================================
     ______________________________ usecase: hello ______________________________
     usecase execution failed
        spec failed: 'some': 'other'
        no further details known at this point.
     ==================== 1 failed, 1 passed in 0.12 seconds ====================
 
 .. regendoc:wipe
@@ -55,23 +55,23 @@ your own domain specific testing languag
     will be reported as a (red) string.
 
 ``reportinfo()`` is used for representing the test location and is also
 consulted when reporting in ``verbose`` mode::
 
     nonpython $ pytest -v
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
-    cachedir: .cache
+    cachedir: .pytest_cache
     rootdir: $REGENDOC_TMPDIR/nonpython, inifile:
     collecting ... collected 2 items
-    
+
     test_simple.yml::hello FAILED                                        [ 50%]
     test_simple.yml::ok PASSED                                           [100%]
-    
+
     ================================= FAILURES =================================
     ______________________________ usecase: hello ______________________________
     usecase execution failed
        spec failed: 'some': 'other'
        no further details known at this point.
     ==================== 1 failed, 1 passed in 0.12 seconds ====================
 
 .. regendoc:wipe
@@ -82,10 +82,10 @@ interesting to just look at the collecti
     nonpython $ pytest --collect-only
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR/nonpython, inifile:
     collected 2 items
     <YamlFile 'test_simple.yml'>
       <YamlItem 'hello'>
       <YamlItem 'ok'>
-    
+
     ======================= no tests ran in 0.12 seconds =======================
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/nonpython/conftest.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/nonpython/conftest.py
@@ -1,40 +1,49 @@
 # content of conftest.py
 
 import pytest
 
+
 def pytest_collect_file(parent, path):
     if path.ext == ".yml" and path.basename.startswith("test"):
         return YamlFile(path, parent)
 
+
 class YamlFile(pytest.File):
+
     def collect(self):
-        import yaml # we need a yaml parser, e.g. PyYAML
+        import yaml  # we need a yaml parser, e.g. PyYAML
+
         raw = yaml.safe_load(self.fspath.open())
         for name, spec in sorted(raw.items()):
             yield YamlItem(name, self, spec)
 
+
 class YamlItem(pytest.Item):
+
     def __init__(self, name, parent, spec):
         super(YamlItem, self).__init__(name, parent)
         self.spec = spec
 
     def runtest(self):
         for name, value in sorted(self.spec.items()):
             # some custom test execution (dumb example follows)
             if name != value:
                 raise YamlException(self, name, value)
 
     def repr_failure(self, excinfo):
         """ called when self.runtest() raises an exception. """
         if isinstance(excinfo.value, YamlException):
-            return "\n".join([
-                "usecase execution failed",
-                "   spec failed: %r: %r" % excinfo.value.args[1:3],
-                "   no further details known at this point."
-            ])
+            return "\n".join(
+                [
+                    "usecase execution failed",
+                    "   spec failed: %r: %r" % excinfo.value.args[1:3],
+                    "   no further details known at this point.",
+                ]
+            )
 
     def reportinfo(self):
         return self.fspath, 0, "usecase: %s" % self.name
 
+
 class YamlException(Exception):
     """ custom exception for error reporting. """
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/parametrize.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/parametrize.rst
@@ -50,23 +50,23 @@ This means that we only run 2 tests if w
 
 We run only two computations, so we see two dots.
 let's run the full monty::
 
     $ pytest -q --all
     ....F                                                                [100%]
     ================================= FAILURES =================================
     _____________________________ test_compute[4] ______________________________
-    
+
     param1 = 4
-    
+
         def test_compute(param1):
     >       assert param1 < 4
     E       assert 4 < 4
-    
+
     test_compute.py:3: AssertionError
     1 failed, 4 passed in 0.12 seconds
 
 As expected when running the full range of ``param1`` values
 we'll get an error on the last one.
 
 
 Different options for test IDs
@@ -146,26 +146,26 @@ objects, they are still using the defaul
       <Function 'test_timedistance_v0[a0-b0-expected0]'>
       <Function 'test_timedistance_v0[a1-b1-expected1]'>
       <Function 'test_timedistance_v1[forward]'>
       <Function 'test_timedistance_v1[backward]'>
       <Function 'test_timedistance_v2[20011212-20011211-expected0]'>
       <Function 'test_timedistance_v2[20011211-20011212-expected1]'>
       <Function 'test_timedistance_v3[forward]'>
       <Function 'test_timedistance_v3[backward]'>
-    
+
     ======================= no tests ran in 0.12 seconds =======================
 
 In ``test_timedistance_v3``, we used ``pytest.param`` to specify the test IDs
 together with the actual data, instead of listing them separately.
 
 A quick port of "testscenarios"
 ------------------------------------
 
-.. _`test scenarios`: http://pypi.python.org/pypi/testscenarios/
+.. _`test scenarios`: https://pypi.org/project/testscenarios/
 
 Here is a quick port to run tests configured with `test scenarios`_,
 an add-on from Robert Collins for the standard unittest framework. We
 only have to work a bit to construct the correct arguments for pytest's
 :py:func:`Metafunc.parametrize`::
 
     # content of test_scenarios.py
 
@@ -193,19 +193,19 @@ only have to work a bit to construct the
 
 this is a fully self-contained example which you can run with::
 
     $ pytest test_scenarios.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 4 items
-    
+
     test_scenarios.py ....                                               [100%]
-    
+
     ========================= 4 passed in 0.12 seconds =========================
 
 If you just collect tests you'll also nicely see 'advanced' and 'basic' as variants for the test function::
 
 
     $ pytest --collect-only test_scenarios.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
@@ -213,17 +213,17 @@ If you just collect tests you'll also ni
     collected 4 items
     <Module 'test_scenarios.py'>
       <Class 'TestSampleWithScenarios'>
         <Instance '()'>
           <Function 'test_demo1[basic]'>
           <Function 'test_demo2[basic]'>
           <Function 'test_demo1[advanced]'>
           <Function 'test_demo2[advanced]'>
-    
+
     ======================= no tests ran in 0.12 seconds =======================
 
 Note that we told ``metafunc.parametrize()`` that your scenario values
 should be considered class-scoped.  With pytest-2.3 this leads to a
 resource-based ordering.
 
 Deferring the setup of parametrized resources
 ---------------------------------------------------
@@ -274,34 +274,34 @@ Let's first see how it looks like at col
     $ pytest test_backends.py --collect-only
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 2 items
     <Module 'test_backends.py'>
       <Function 'test_db_initialized[d1]'>
       <Function 'test_db_initialized[d2]'>
-    
+
     ======================= no tests ran in 0.12 seconds =======================
 
 And then when we run the test::
 
     $ pytest -q test_backends.py
     .F                                                                   [100%]
     ================================= FAILURES =================================
     _________________________ test_db_initialized[d2] __________________________
-    
+
     db = <conftest.DB2 object at 0xdeadbeef>
-    
+
         def test_db_initialized(db):
             # a dummy test
             if db.__class__.__name__ == "DB2":
     >           pytest.fail("deliberately failing for demo purposes")
     E           Failed: deliberately failing for demo purposes
-    
+
     test_backends.py:6: Failed
     1 failed, 1 passed in 0.12 seconds
 
 The first invocation with ``db == "DB1"`` passed while the second with ``db == "DB2"`` failed.  Our ``db`` fixture function has instantiated each of the DB values during the setup phase while the ``pytest_generate_tests`` generated two according calls to the ``test_db_initialized`` during the collection phase.
 
 .. regendoc:wipe
 
 Apply indirect on particular arguments
@@ -334,17 +334,17 @@ The result of this test will be successf
 
     $ pytest test_indirect_list.py --collect-only
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 1 item
     <Module 'test_indirect_list.py'>
       <Function 'test_indirect[a-b]'>
-    
+
     ======================= no tests ran in 0.12 seconds =======================
 
 .. regendoc:wipe
 
 Parametrizing test methods through per-class configuration
 --------------------------------------------------------------
 
 .. _`unittest parametrizer`: https://github.com/testing-cabal/unittest-ext/blob/master/params.py
@@ -379,23 +379,23 @@ parametrizer`_ but in a lot less code::
 
 Our test generator looks up a class-level definition which specifies which
 argument sets to use for each test function.  Let's run it::
 
     $ pytest -q
     F..                                                                  [100%]
     ================================= FAILURES =================================
     ________________________ TestClass.test_equals[1-2] ________________________
-    
+
     self = <test_parametrize.TestClass object at 0xdeadbeef>, a = 1, b = 2
-    
+
         def test_equals(self, a, b):
     >       assert a == b
     E       assert 1 == 2
-    
+
     test_parametrize.py:18: AssertionError
     1 failed, 2 passed in 0.12 seconds
 
 Indirect parametrization with multiple fixtures
 --------------------------------------------------------------
 
 Here is a stripped down real-life example of using parametrized
 testing for testing serialization of objects between different python
@@ -457,24 +457,24 @@ And finally a little test module::
 
 If you run this with reporting for skips enabled::
 
     $ pytest -rs test_module.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 2 items
-    
+
     test_module.py .s                                                    [100%]
     ========================= short test summary info ==========================
     SKIP [1] $REGENDOC_TMPDIR/conftest.py:11: could not import 'opt2'
-    
+
     =================== 1 passed, 1 skipped in 0.12 seconds ====================
 
-You'll see that we don't have a ``opt2`` module and thus the second test run
+You'll see that we don't have an ``opt2`` module and thus the second test run
 of our ``test_func1`` was skipped.  A few notes:
 
 - the fixture functions in the ``conftest.py`` file are "session-scoped" because we
   don't need to import more than once
 
 - if you have multiple test functions and a skipped import, you will see
   the ``[1]`` count increasing in the report
 
@@ -499,20 +499,20 @@ For example::
                      marks=pytest.mark.basic,
                      id='basic_2+4'),
         pytest.param('6*9', 42,
                      marks=[pytest.mark.basic, pytest.mark.xfail],
                      id='basic_6*9'),
     ])
     def test_eval(test_input, expected):
         assert eval(test_input) == expected
-    
+
 In this example, we have 4 parametrized tests. Except for the first test,
 we mark the rest three parametrized tests with the custom marker ``basic``,
-and for the fourth test we also use the built-in mark ``xfail`` to indicate this 
+and for the fourth test we also use the built-in mark ``xfail`` to indicate this
 test is expected to fail. For explicitness, we set test ids for some tests.
 
 Then run ``pytest`` with verbose mode and with only the ``basic`` marker::
 
     pytest -v -m basic
     ============================================ test session starts =============================================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/py2py3/conftest.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/py2py3/conftest.py
@@ -1,16 +1,16 @@
 import sys
 import pytest
 
 py3 = sys.version_info[0] >= 3
 
+
 class DummyCollector(pytest.collect.File):
+
     def collect(self):
         return []
 
+
 def pytest_pycollect_makemodule(path, parent):
     bn = path.basename
     if "py3" in bn and not py3 or ("py2" in bn and py3):
         return DummyCollector(path, parent=parent)
-
-
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/py2py3/test_py2.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/py2py3/test_py2.py
@@ -1,7 +1,6 @@
 
 def test_exception_syntax():
     try:
         0/0
     except ZeroDivisionError, e:
         pass
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/py2py3/test_py3.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/py2py3/test_py3.py
@@ -1,7 +1,5 @@
-
 def test_exception_syntax():
     try:
-        0/0
+        0 / 0
     except ZeroDivisionError as e:
         pass
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/pythoncollection.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/pythoncollection.py
@@ -1,11 +1,15 @@
-
 # run this with $ pytest --collect-only test_collectonly.py
 #
+
+
 def test_function():
     pass
 
+
 class TestClass(object):
+
     def test_method(self):
         pass
+
     def test_anothermethod(self):
         pass
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/pythoncollection.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/pythoncollection.rst
@@ -34,45 +34,53 @@ you will see that ``pytest`` only collec
     tests/example/test_example_01.py .
     tests/example/test_example_02.py .
     tests/example/test_example_03.py .
     tests/foobar/test_foobar_01.py .
     tests/foobar/test_foobar_02.py .
 
     ======= 5 passed in 0.02 seconds =======
 
+Deselect tests during test collection
+-------------------------------------
+
+Tests can individually be deselected during collection by passing the ``--deselect=item`` option.
+For example, say ``tests/foobar/test_foobar_01.py`` contains ``test_a`` and ``test_b``.
+You can run all of the tests within ``tests/`` *except* for ``tests/foobar/test_foobar_01.py::test_a``
+by invoking ``pytest`` with ``--deselect tests/foobar/test_foobar_01.py::test_a``.
+``pytest`` allows multiple ``--deselect`` options.
 
 Keeping duplicate paths specified from command line
 ----------------------------------------------------
 
 Default behavior of ``pytest`` is to ignore duplicate paths specified from the command line.
 Example::
 
-    py.test path_a path_a
+    pytest path_a path_a
 
     ...
     collected 1 item
     ...
 
 Just collect tests once.
 
 To collect duplicate tests, use the ``--keep-duplicates`` option on the cli.
 Example::
 
-    py.test --keep-duplicates path_a path_a
+    pytest --keep-duplicates path_a path_a
 
     ...
     collected 2 items
     ...
 
 As the collector just works on directories, if you specify twice a single test file, ``pytest`` will
 still collect it twice, no matter if the ``--keep-duplicates`` is not specified.
 Example::
 
-    py.test test_a.py test_a.py
+    pytest test_a.py test_a.py
 
     ...
     collected 2 items
     ...
 
 
 Changing directory recursion
 -----------------------------------------------------
@@ -120,17 +128,17 @@ then the test collection looks like this
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini
     collected 2 items
     <Module 'check_myapp.py'>
       <Class 'CheckMyApp'>
         <Instance '()'>
           <Function 'simple_check'>
           <Function 'complex_check'>
-    
+
     ======================= no tests ran in 0.12 seconds =======================
 
 .. note::
 
    the ``python_functions`` and ``python_classes`` options has no effect
    for ``unittest.TestCase`` test discovery because pytest delegates
    detection of test case methods to unittest code.
 
@@ -167,17 +175,17 @@ You can always peek at the collection tr
     rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini
     collected 3 items
     <Module 'CWD/pythoncollection.py'>
       <Function 'test_function'>
       <Class 'TestClass'>
         <Instance '()'>
           <Function 'test_method'>
           <Function 'test_anothermethod'>
-    
+
     ======================= no tests ran in 0.12 seconds =======================
 
 .. _customizing-test-collection:
 
 Customizing test collection
 ---------------------------
 
 .. regendoc:wipe
@@ -230,10 +238,10 @@ leave out the ``setup.py`` file::
 If you run with a Python 3 interpreter both the one test and the ``setup.py``
 file will be left out::
 
     $ pytest --collect-only
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini
     collected 0 items
-    
+
     ======================= no tests ran in 0.12 seconds =======================
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/reportingdemo.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/reportingdemo.rst
@@ -9,596 +9,625 @@ and how ``pytest`` presents things (unfo
 not showing the nice colors here in the HTML that you
 get on the terminal - we are working on that)::
 
     assertion $ pytest failure_demo.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR/assertion, inifile:
     collected 42 items
-    
+
     failure_demo.py FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF           [100%]
-    
+
     ================================= FAILURES =================================
     ____________________________ test_generative[0] ____________________________
-    
+
     param1 = 3, param2 = 6
-    
+
         def test_generative(param1, param2):
     >       assert param1 * 2 < param2
     E       assert (3 * 2) < 6
-    
-    failure_demo.py:16: AssertionError
+
+    failure_demo.py:19: AssertionError
     _________________________ TestFailing.test_simple __________________________
-    
+
     self = <failure_demo.TestFailing object at 0xdeadbeef>
-    
+
         def test_simple(self):
+
             def f():
                 return 42
+
             def g():
                 return 43
-        
+
     >       assert f() == g()
     E       assert 42 == 43
     E        +  where 42 = <function TestFailing.test_simple.<locals>.f at 0xdeadbeef>()
     E        +  and   43 = <function TestFailing.test_simple.<locals>.g at 0xdeadbeef>()
-    
-    failure_demo.py:29: AssertionError
+
+    failure_demo.py:37: AssertionError
     ____________________ TestFailing.test_simple_multiline _____________________
-    
+
     self = <failure_demo.TestFailing object at 0xdeadbeef>
-    
+
         def test_simple_multiline(self):
-            otherfunc_multi(
-                      42,
-    >                 6*9)
-    
-    failure_demo.py:34: 
-    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
-    
+    >       otherfunc_multi(42, 6 * 9)
+
+    failure_demo.py:40:
+    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
+
     a = 42, b = 54
-    
-        def otherfunc_multi(a,b):
-    >       assert (a ==
-                    b)
+
+        def otherfunc_multi(a, b):
+    >       assert a == b
     E       assert 42 == 54
-    
-    failure_demo.py:12: AssertionError
+
+    failure_demo.py:15: AssertionError
     ___________________________ TestFailing.test_not ___________________________
-    
+
     self = <failure_demo.TestFailing object at 0xdeadbeef>
-    
+
         def test_not(self):
+
             def f():
                 return 42
+
     >       assert not f()
     E       assert not 42
     E        +  where 42 = <function TestFailing.test_not.<locals>.f at 0xdeadbeef>()
-    
-    failure_demo.py:39: AssertionError
+
+    failure_demo.py:47: AssertionError
     _________________ TestSpecialisedExplanations.test_eq_text _________________
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_eq_text(self):
-    >       assert 'spam' == 'eggs'
+    >       assert "spam" == "eggs"
     E       AssertionError: assert 'spam' == 'eggs'
     E         - spam
     E         + eggs
-    
-    failure_demo.py:43: AssertionError
+
+    failure_demo.py:53: AssertionError
     _____________ TestSpecialisedExplanations.test_eq_similar_text _____________
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_eq_similar_text(self):
-    >       assert 'foo 1 bar' == 'foo 2 bar'
+    >       assert "foo 1 bar" == "foo 2 bar"
     E       AssertionError: assert 'foo 1 bar' == 'foo 2 bar'
     E         - foo 1 bar
     E         ?     ^
     E         + foo 2 bar
     E         ?     ^
-    
-    failure_demo.py:46: AssertionError
+
+    failure_demo.py:56: AssertionError
     ____________ TestSpecialisedExplanations.test_eq_multiline_text ____________
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_eq_multiline_text(self):
-    >       assert 'foo\nspam\nbar' == 'foo\neggs\nbar'
+    >       assert "foo\nspam\nbar" == "foo\neggs\nbar"
     E       AssertionError: assert 'foo\nspam\nbar' == 'foo\neggs\nbar'
     E           foo
     E         - spam
     E         + eggs
     E           bar
-    
-    failure_demo.py:49: AssertionError
+
+    failure_demo.py:59: AssertionError
     ______________ TestSpecialisedExplanations.test_eq_long_text _______________
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_eq_long_text(self):
-            a = '1'*100 + 'a' + '2'*100
-            b = '1'*100 + 'b' + '2'*100
+            a = "1" * 100 + "a" + "2" * 100
+            b = "1" * 100 + "b" + "2" * 100
     >       assert a == b
     E       AssertionError: assert '111111111111...2222222222222' == '1111111111111...2222222222222'
     E         Skipping 90 identical leading characters in diff, use -v to show
     E         Skipping 91 identical trailing characters in diff, use -v to show
     E         - 1111111111a222222222
     E         ?           ^
     E         + 1111111111b222222222
     E         ?           ^
-    
-    failure_demo.py:54: AssertionError
+
+    failure_demo.py:64: AssertionError
     _________ TestSpecialisedExplanations.test_eq_long_text_multiline __________
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_eq_long_text_multiline(self):
-            a = '1\n'*100 + 'a' + '2\n'*100
-            b = '1\n'*100 + 'b' + '2\n'*100
+            a = "1\n" * 100 + "a" + "2\n" * 100
+            b = "1\n" * 100 + "b" + "2\n" * 100
     >       assert a == b
     E       AssertionError: assert '1\n1\n1\n1\n...n2\n2\n2\n2\n' == '1\n1\n1\n1\n1...n2\n2\n2\n2\n'
     E         Skipping 190 identical leading characters in diff, use -v to show
     E         Skipping 191 identical trailing characters in diff, use -v to show
     E           1
     E           1
     E           1
     E           1
     E           1...
-    E         
+    E
     E         ...Full output truncated (7 lines hidden), use '-vv' to show
-    
-    failure_demo.py:59: AssertionError
+
+    failure_demo.py:69: AssertionError
     _________________ TestSpecialisedExplanations.test_eq_list _________________
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_eq_list(self):
     >       assert [0, 1, 2] == [0, 1, 3]
     E       assert [0, 1, 2] == [0, 1, 3]
     E         At index 2 diff: 2 != 3
     E         Use -v to get the full diff
-    
-    failure_demo.py:62: AssertionError
+
+    failure_demo.py:72: AssertionError
     ______________ TestSpecialisedExplanations.test_eq_list_long _______________
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_eq_list_long(self):
-            a = [0]*100 + [1] + [3]*100
-            b = [0]*100 + [2] + [3]*100
+            a = [0] * 100 + [1] + [3] * 100
+            b = [0] * 100 + [2] + [3] * 100
     >       assert a == b
     E       assert [0, 0, 0, 0, 0, 0, ...] == [0, 0, 0, 0, 0, 0, ...]
     E         At index 100 diff: 1 != 2
     E         Use -v to get the full diff
-    
-    failure_demo.py:67: AssertionError
+
+    failure_demo.py:77: AssertionError
     _________________ TestSpecialisedExplanations.test_eq_dict _________________
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_eq_dict(self):
-    >       assert {'a': 0, 'b': 1, 'c': 0} == {'a': 0, 'b': 2, 'd': 0}
+    >       assert {"a": 0, "b": 1, "c": 0} == {"a": 0, "b": 2, "d": 0}
     E       AssertionError: assert {'a': 0, 'b': 1, 'c': 0} == {'a': 0, 'b': 2, 'd': 0}
     E         Omitting 1 identical items, use -vv to show
     E         Differing items:
     E         {'b': 1} != {'b': 2}
     E         Left contains more items:
     E         {'c': 0}
     E         Right contains more items:
     E         {'d': 0}...
-    E         
+    E
     E         ...Full output truncated (2 lines hidden), use '-vv' to show
-    
-    failure_demo.py:70: AssertionError
+
+    failure_demo.py:80: AssertionError
     _________________ TestSpecialisedExplanations.test_eq_set __________________
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_eq_set(self):
-    >       assert set([0, 10, 11, 12]) == set([0, 20, 21])
+    >       assert {0, 10, 11, 12} == {0, 20, 21}
     E       AssertionError: assert {0, 10, 11, 12} == {0, 20, 21}
     E         Extra items in the left set:
     E         10
     E         11
     E         12
     E         Extra items in the right set:
     E         20
     E         21...
-    E         
+    E
     E         ...Full output truncated (2 lines hidden), use '-vv' to show
-    
-    failure_demo.py:73: AssertionError
+
+    failure_demo.py:83: AssertionError
     _____________ TestSpecialisedExplanations.test_eq_longer_list ______________
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_eq_longer_list(self):
-    >       assert [1,2] == [1,2,3]
+    >       assert [1, 2] == [1, 2, 3]
     E       assert [1, 2] == [1, 2, 3]
     E         Right contains more items, first extra item: 3
     E         Use -v to get the full diff
-    
-    failure_demo.py:76: AssertionError
+
+    failure_demo.py:86: AssertionError
     _________________ TestSpecialisedExplanations.test_in_list _________________
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_in_list(self):
     >       assert 1 in [0, 2, 3, 4, 5]
     E       assert 1 in [0, 2, 3, 4, 5]
-    
-    failure_demo.py:79: AssertionError
+
+    failure_demo.py:89: AssertionError
     __________ TestSpecialisedExplanations.test_not_in_text_multiline __________
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_not_in_text_multiline(self):
-            text = 'some multiline\ntext\nwhich\nincludes foo\nand a\ntail'
-    >       assert 'foo' not in text
+            text = "some multiline\ntext\nwhich\nincludes foo\nand a\ntail"
+    >       assert "foo" not in text
     E       AssertionError: assert 'foo' not in 'some multiline\ntext\nw...ncludes foo\nand a\ntail'
     E         'foo' is contained here:
     E           some multiline
     E           text
     E           which
     E           includes foo
     E         ?          +++
     E           and a...
-    E         
+    E
     E         ...Full output truncated (2 lines hidden), use '-vv' to show
-    
-    failure_demo.py:83: AssertionError
+
+    failure_demo.py:93: AssertionError
     ___________ TestSpecialisedExplanations.test_not_in_text_single ____________
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_not_in_text_single(self):
-            text = 'single foo line'
-    >       assert 'foo' not in text
+            text = "single foo line"
+    >       assert "foo" not in text
     E       AssertionError: assert 'foo' not in 'single foo line'
     E         'foo' is contained here:
     E           single foo line
     E         ?        +++
-    
-    failure_demo.py:87: AssertionError
+
+    failure_demo.py:97: AssertionError
     _________ TestSpecialisedExplanations.test_not_in_text_single_long _________
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_not_in_text_single_long(self):
-            text = 'head ' * 50 + 'foo ' + 'tail ' * 20
-    >       assert 'foo' not in text
+            text = "head " * 50 + "foo " + "tail " * 20
+    >       assert "foo" not in text
     E       AssertionError: assert 'foo' not in 'head head head head hea...ail tail tail tail tail '
     E         'foo' is contained here:
-    E           head head foo tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail 
+    E           head head foo tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail
     E         ?           +++
-    
-    failure_demo.py:91: AssertionError
+
+    failure_demo.py:101: AssertionError
     ______ TestSpecialisedExplanations.test_not_in_text_single_long_term _______
-    
+
     self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
-    
+
         def test_not_in_text_single_long_term(self):
-            text = 'head ' * 50 + 'f'*70 + 'tail ' * 20
-    >       assert 'f'*70 not in text
+            text = "head " * 50 + "f" * 70 + "tail " * 20
+    >       assert "f" * 70 not in text
     E       AssertionError: assert 'fffffffffff...ffffffffffff' not in 'head head he...l tail tail '
     E         'ffffffffffffffffff...fffffffffffffffffff' is contained here:
-    E           head head fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffftail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail 
+    E           head head fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffftail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail
     E         ?           ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-    
-    failure_demo.py:95: AssertionError
+
+    failure_demo.py:105: AssertionError
     ______________________________ test_attribute ______________________________
-    
+
         def test_attribute():
+
             class Foo(object):
                 b = 1
+
             i = Foo()
     >       assert i.b == 2
     E       assert 1 == 2
     E        +  where 1 = <failure_demo.test_attribute.<locals>.Foo object at 0xdeadbeef>.b
-    
-    failure_demo.py:102: AssertionError
+
+    failure_demo.py:114: AssertionError
     _________________________ test_attribute_instance __________________________
-    
+
         def test_attribute_instance():
+
             class Foo(object):
                 b = 1
+
     >       assert Foo().b == 2
     E       AssertionError: assert 1 == 2
     E        +  where 1 = <failure_demo.test_attribute_instance.<locals>.Foo object at 0xdeadbeef>.b
     E        +    where <failure_demo.test_attribute_instance.<locals>.Foo object at 0xdeadbeef> = <class 'failure_demo.test_attribute_instance.<locals>.Foo'>()
-    
-    failure_demo.py:108: AssertionError
+
+    failure_demo.py:122: AssertionError
     __________________________ test_attribute_failure __________________________
-    
+
         def test_attribute_failure():
+
             class Foo(object):
+
                 def _get_b(self):
-                    raise Exception('Failed to get attrib')
+                    raise Exception("Failed to get attrib")
+
                 b = property(_get_b)
+
             i = Foo()
     >       assert i.b == 2
-    
-    failure_demo.py:117: 
-    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
-    
+
+    failure_demo.py:135:
+    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
+
     self = <failure_demo.test_attribute_failure.<locals>.Foo object at 0xdeadbeef>
-    
+
         def _get_b(self):
-    >       raise Exception('Failed to get attrib')
+    >       raise Exception("Failed to get attrib")
     E       Exception: Failed to get attrib
-    
-    failure_demo.py:114: Exception
+
+    failure_demo.py:130: Exception
     _________________________ test_attribute_multiple __________________________
-    
+
         def test_attribute_multiple():
+
             class Foo(object):
                 b = 1
+
             class Bar(object):
                 b = 2
+
     >       assert Foo().b == Bar().b
     E       AssertionError: assert 1 == 2
     E        +  where 1 = <failure_demo.test_attribute_multiple.<locals>.Foo object at 0xdeadbeef>.b
     E        +    where <failure_demo.test_attribute_multiple.<locals>.Foo object at 0xdeadbeef> = <class 'failure_demo.test_attribute_multiple.<locals>.Foo'>()
     E        +  and   2 = <failure_demo.test_attribute_multiple.<locals>.Bar object at 0xdeadbeef>.b
     E        +    where <failure_demo.test_attribute_multiple.<locals>.Bar object at 0xdeadbeef> = <class 'failure_demo.test_attribute_multiple.<locals>.Bar'>()
-    
-    failure_demo.py:125: AssertionError
+
+    failure_demo.py:146: AssertionError
     __________________________ TestRaises.test_raises __________________________
-    
+
     self = <failure_demo.TestRaises object at 0xdeadbeef>
-    
+
         def test_raises(self):
-            s = 'qwe'
+            s = "qwe"  # NOQA
     >       raises(TypeError, "int(s)")
-    
-    failure_demo.py:134: 
-    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
-    
+
+    failure_demo.py:157:
+    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
+
     >   int(s)
     E   ValueError: invalid literal for int() with base 10: 'qwe'
-    
-    <0-codegen $PYTHON_PREFIX/lib/python3.5/site-packages/_pytest/python_api.py:580>:1: ValueError
+
+    <0-codegen $PYTHON_PREFIX/lib/python3.5/site-packages/_pytest/python_api.py:634>:1: ValueError
     ______________________ TestRaises.test_raises_doesnt _______________________
-    
+
     self = <failure_demo.TestRaises object at 0xdeadbeef>
-    
+
         def test_raises_doesnt(self):
     >       raises(IOError, "int('3')")
     E       Failed: DID NOT RAISE <class 'OSError'>
-    
-    failure_demo.py:137: Failed
+
+    failure_demo.py:160: Failed
     __________________________ TestRaises.test_raise ___________________________
-    
+
     self = <failure_demo.TestRaises object at 0xdeadbeef>
-    
+
         def test_raise(self):
     >       raise ValueError("demo error")
     E       ValueError: demo error
-    
-    failure_demo.py:140: ValueError
+
+    failure_demo.py:163: ValueError
     ________________________ TestRaises.test_tupleerror ________________________
-    
+
     self = <failure_demo.TestRaises object at 0xdeadbeef>
-    
+
         def test_tupleerror(self):
-    >       a,b = [1]
+    >       a, b = [1]  # NOQA
     E       ValueError: not enough values to unpack (expected 2, got 1)
-    
-    failure_demo.py:143: ValueError
+
+    failure_demo.py:166: ValueError
     ______ TestRaises.test_reinterpret_fails_with_print_for_the_fun_of_it ______
-    
+
     self = <failure_demo.TestRaises object at 0xdeadbeef>
-    
+
         def test_reinterpret_fails_with_print_for_the_fun_of_it(self):
-            l = [1,2,3]
-            print ("l is %r" % l)
-    >       a,b = l.pop()
+            items = [1, 2, 3]
+            print("items is %r" % items)
+    >       a, b = items.pop()
     E       TypeError: 'int' object is not iterable
-    
-    failure_demo.py:148: TypeError
+
+    failure_demo.py:171: TypeError
     --------------------------- Captured stdout call ---------------------------
-    l is [1, 2, 3]
+    items is [1, 2, 3]
     ________________________ TestRaises.test_some_error ________________________
-    
+
     self = <failure_demo.TestRaises object at 0xdeadbeef>
-    
+
         def test_some_error(self):
-    >       if namenotexi:
+    >       if namenotexi:  # NOQA
     E       NameError: name 'namenotexi' is not defined
-    
-    failure_demo.py:151: NameError
+
+    failure_demo.py:174: NameError
     ____________________ test_dynamic_compile_shows_nicely _____________________
-    
+
         def test_dynamic_compile_shows_nicely():
-            src = 'def foo():\n assert 1 == 0\n'
-            name = 'abc-123'
-            module = py.std.imp.new_module(name)
-            code = _pytest._code.compile(src, name, 'exec')
+            import imp
+            import sys
+
+            src = "def foo():\n assert 1 == 0\n"
+            name = "abc-123"
+            module = imp.new_module(name)
+            code = _pytest._code.compile(src, name, "exec")
             py.builtin.exec_(code, module.__dict__)
-            py.std.sys.modules[name] = module
+            sys.modules[name] = module
     >       module.foo()
-    
-    failure_demo.py:166: 
-    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
-    
+
+    failure_demo.py:192:
+    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
+
         def foo():
     >    assert 1 == 0
     E    AssertionError
-    
-    <2-codegen 'abc-123' $REGENDOC_TMPDIR/assertion/failure_demo.py:163>:2: AssertionError
+
+    <2-codegen 'abc-123' $REGENDOC_TMPDIR/assertion/failure_demo.py:189>:2: AssertionError
     ____________________ TestMoreErrors.test_complex_error _____________________
-    
+
     self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
-    
+
         def test_complex_error(self):
+
             def f():
                 return 44
+
             def g():
                 return 43
+
     >       somefunc(f(), g())
-    
-    failure_demo.py:176: 
-    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
-    failure_demo.py:9: in somefunc
-        otherfunc(x,y)
-    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
-    
+
+    failure_demo.py:205:
+    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
+    failure_demo.py:11: in somefunc
+        otherfunc(x, y)
+    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
+
     a = 44, b = 43
-    
-        def otherfunc(a,b):
-    >       assert a==b
+
+        def otherfunc(a, b):
+    >       assert a == b
     E       assert 44 == 43
-    
-    failure_demo.py:6: AssertionError
+
+    failure_demo.py:7: AssertionError
     ___________________ TestMoreErrors.test_z1_unpack_error ____________________
-    
+
     self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
-    
+
         def test_z1_unpack_error(self):
-            l = []
-    >       a,b  = l
+            items = []
+    >       a, b = items
     E       ValueError: not enough values to unpack (expected 2, got 0)
-    
-    failure_demo.py:180: ValueError
+
+    failure_demo.py:209: ValueError
     ____________________ TestMoreErrors.test_z2_type_error _____________________
-    
+
     self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
-    
+
         def test_z2_type_error(self):
-            l = 3
-    >       a,b  = l
+            items = 3
+    >       a, b = items
     E       TypeError: 'int' object is not iterable
-    
-    failure_demo.py:184: TypeError
+
+    failure_demo.py:213: TypeError
     ______________________ TestMoreErrors.test_startswith ______________________
-    
+
     self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
-    
+
         def test_startswith(self):
             s = "123"
             g = "456"
     >       assert s.startswith(g)
     E       AssertionError: assert False
     E        +  where False = <built-in method startswith of str object at 0xdeadbeef>('456')
     E        +    where <built-in method startswith of str object at 0xdeadbeef> = '123'.startswith
-    
-    failure_demo.py:189: AssertionError
+
+    failure_demo.py:218: AssertionError
     __________________ TestMoreErrors.test_startswith_nested ___________________
-    
+
     self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
-    
+
         def test_startswith_nested(self):
+
             def f():
                 return "123"
+
             def g():
                 return "456"
+
     >       assert f().startswith(g())
     E       AssertionError: assert False
     E        +  where False = <built-in method startswith of str object at 0xdeadbeef>('456')
     E        +    where <built-in method startswith of str object at 0xdeadbeef> = '123'.startswith
     E        +      where '123' = <function TestMoreErrors.test_startswith_nested.<locals>.f at 0xdeadbeef>()
     E        +    and   '456' = <function TestMoreErrors.test_startswith_nested.<locals>.g at 0xdeadbeef>()
-    
-    failure_demo.py:196: AssertionError
+
+    failure_demo.py:228: AssertionError
     _____________________ TestMoreErrors.test_global_func ______________________
-    
+
     self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
-    
+
         def test_global_func(self):
     >       assert isinstance(globf(42), float)
     E       assert False
     E        +  where False = isinstance(43, float)
     E        +    where 43 = globf(42)
-    
-    failure_demo.py:199: AssertionError
+
+    failure_demo.py:231: AssertionError
     _______________________ TestMoreErrors.test_instance _______________________
-    
+
     self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
-    
+
         def test_instance(self):
-            self.x = 6*7
+            self.x = 6 * 7
     >       assert self.x != 42
     E       assert 42 != 42
     E        +  where 42 = <failure_demo.TestMoreErrors object at 0xdeadbeef>.x
-    
-    failure_demo.py:203: AssertionError
+
+    failure_demo.py:235: AssertionError
     _______________________ TestMoreErrors.test_compare ________________________
-    
+
     self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
-    
+
         def test_compare(self):
     >       assert globf(10) < 5
     E       assert 11 < 5
     E        +  where 11 = globf(10)
-    
-    failure_demo.py:206: AssertionError
+
+    failure_demo.py:238: AssertionError
     _____________________ TestMoreErrors.test_try_finally ______________________
-    
+
     self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
-    
+
         def test_try_finally(self):
             x = 1
             try:
     >           assert x == 0
     E           assert 1 == 0
-    
-    failure_demo.py:211: AssertionError
+
+    failure_demo.py:243: AssertionError
     ___________________ TestCustomAssertMsg.test_single_line ___________________
-    
+
     self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef>
-    
+
         def test_single_line(self):
+
             class A(object):
                 a = 1
+
             b = 2
     >       assert A.a == b, "A.a appears not to be b"
     E       AssertionError: A.a appears not to be b
     E       assert 1 == 2
     E        +  where 1 = <class 'failure_demo.TestCustomAssertMsg.test_single_line.<locals>.A'>.a
-    
-    failure_demo.py:222: AssertionError
+
+    failure_demo.py:256: AssertionError
     ____________________ TestCustomAssertMsg.test_multiline ____________________
-    
+
     self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef>
-    
+
         def test_multiline(self):
+
             class A(object):
                 a = 1
+
             b = 2
-    >       assert A.a == b, "A.a appears not to be b\n" \
-                "or does not appear to be b\none of those"
+    >       assert (
+                A.a == b
+            ), "A.a appears not to be b\n" "or does not appear to be b\none of those"
     E       AssertionError: A.a appears not to be b
     E         or does not appear to be b
     E         one of those
     E       assert 1 == 2
     E        +  where 1 = <class 'failure_demo.TestCustomAssertMsg.test_multiline.<locals>.A'>.a
-    
-    failure_demo.py:228: AssertionError
+
+    failure_demo.py:264: AssertionError
     ___________________ TestCustomAssertMsg.test_custom_repr ___________________
-    
+
     self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef>
-    
+
         def test_custom_repr(self):
+
             class JSON(object):
                 a = 1
+
                 def __repr__(self):
                     return "This is JSON\n{\n  'foo': 'bar'\n}"
+
             a = JSON()
             b = 2
     >       assert a.a == b, a
     E       AssertionError: This is JSON
     E         {
     E           'foo': 'bar'
     E         }
     E       assert 1 == 2
     E        +  where 1 = This is JSON\n{\n  'foo': 'bar'\n}.a
-    
-    failure_demo.py:238: AssertionError
+
+    failure_demo.py:278: AssertionError
     ============================= warnings summary =============================
-    None
+    <undetermined location>
       Metafunc.addcall is deprecated and scheduled to be removed in pytest 4.0.
       Please use Metafunc.parametrize instead.
-    
+
     -- Docs: http://doc.pytest.org/en/latest/warnings.html
     ================== 42 failed, 1 warnings in 0.12 seconds ===================
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/simple.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/simple.rst
@@ -1,87 +1,92 @@
 
 
 Basic patterns and examples
 ==========================================================
 
+.. _request example:
+
 Pass different values to a test function, depending on command line options
 ----------------------------------------------------------------------------
 
 .. regendoc:wipe
 
 Suppose we want to write a test that depends on a command line option.
 Here is a basic pattern to achieve this:
 
 .. code-block:: python
 
     # content of test_sample.py
     def test_answer(cmdopt):
         if cmdopt == "type1":
-            print ("first")
+            print("first")
         elif cmdopt == "type2":
-            print ("second")
-        assert 0 # to see what was printed
+            print("second")
+        assert 0  # to see what was printed
 
 
 For this to work we need to add a command line option and
 provide the ``cmdopt`` through a :ref:`fixture function <fixture function>`:
 
 .. code-block:: python
 
     # content of conftest.py
     import pytest
 
+
     def pytest_addoption(parser):
-        parser.addoption("--cmdopt", action="store", default="type1",
-            help="my option: type1 or type2")
+        parser.addoption(
+            "--cmdopt", action="store", default="type1", help="my option: type1 or type2"
+        )
+
 
     @pytest.fixture
     def cmdopt(request):
         return request.config.getoption("--cmdopt")
 
 Let's run this without supplying our new option::
 
     $ pytest -q test_sample.py
     F                                                                    [100%]
     ================================= FAILURES =================================
     _______________________________ test_answer ________________________________
-    
+
     cmdopt = 'type1'
-    
+
         def test_answer(cmdopt):
             if cmdopt == "type1":
-                print ("first")
+                print("first")
             elif cmdopt == "type2":
-                print ("second")
-    >       assert 0 # to see what was printed
+                print("second")
+    >       assert 0  # to see what was printed
     E       assert 0
-    
+
     test_sample.py:6: AssertionError
     --------------------------- Captured stdout call ---------------------------
     first
     1 failed in 0.12 seconds
 
 And now with supplying a command line option::
 
     $ pytest -q --cmdopt=type2
     F                                                                    [100%]
     ================================= FAILURES =================================
     _______________________________ test_answer ________________________________
-    
+
     cmdopt = 'type2'
-    
+
         def test_answer(cmdopt):
             if cmdopt == "type1":
-                print ("first")
+                print("first")
             elif cmdopt == "type2":
-                print ("second")
-    >       assert 0 # to see what was printed
+                print("second")
+    >       assert 0  # to see what was printed
     E       assert 0
-    
+
     test_sample.py:6: AssertionError
     --------------------------- Captured stdout call ---------------------------
     second
     1 failed in 0.12 seconds
 
 You can see that the command line option arrived in our test.  This
 completes the basic pattern.  However, one often rather wants to process
 command line options outside of the test and rather pass in different or
@@ -95,33 +100,36 @@ Dynamically adding command line options
 Through :confval:`addopts` you can statically add command line
 options for your project.  You can also dynamically modify
 the command line arguments before they get processed:
 
 .. code-block:: python
 
     # content of conftest.py
     import sys
-    def pytest_cmdline_preparse(args):
-        if 'xdist' in sys.modules: # pytest-xdist plugin
+
+
+    def pytest_load_initial_conftests(args):
+        if "xdist" in sys.modules:  # pytest-xdist plugin
             import multiprocessing
+
             num = max(multiprocessing.cpu_count() / 2, 1)
             args[:] = ["-n", str(num)] + args
 
-If you have the `xdist plugin <https://pypi.python.org/pypi/pytest-xdist>`_ installed
+If you have the `xdist plugin <https://pypi.org/project/pytest-xdist/>`_ installed
 you will now always perform test runs using a number
 of subprocesses close to your CPU. Running in an empty
 directory with the above conftest.py::
 
     $ pytest
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 0 items
-    
+
     ======================= no tests ran in 0.12 seconds =======================
 
 .. _`excontrolskip`:
 
 Control skipping of tests according to command line option
 --------------------------------------------------------------
 
 .. regendoc:wipe
@@ -129,19 +137,23 @@ Control skipping of tests according to c
 Here is a ``conftest.py`` file adding a ``--runslow`` command
 line option to control skipping of ``pytest.mark.slow`` marked tests:
 
 .. code-block:: python
 
     # content of conftest.py
 
     import pytest
+
+
     def pytest_addoption(parser):
-        parser.addoption("--runslow", action="store_true",
-                         default=False, help="run slow tests")
+        parser.addoption(
+            "--runslow", action="store_true", default=False, help="run slow tests"
+        )
+
 
     def pytest_collection_modifyitems(config, items):
         if config.getoption("--runslow"):
             # --runslow given in cli: do not skip slow tests
             return
         skip_slow = pytest.mark.skip(reason="need --runslow option to run")
         for item in items:
             if "slow" in item.keywords:
@@ -165,33 +177,33 @@ We can now write a test module like this
 
 and when running it will see a skipped "slow" test::
 
     $ pytest -rs    # "-rs" means report details on the little 's'
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 2 items
-    
+
     test_module.py .s                                                    [100%]
     ========================= short test summary info ==========================
     SKIP [1] test_module.py:8: need --runslow option to run
-    
+
     =================== 1 passed, 1 skipped in 0.12 seconds ====================
 
 Or run it including the ``slow`` marked test::
 
     $ pytest --runslow
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 2 items
-    
+
     test_module.py ..                                                    [100%]
-    
+
     ========================= 2 passed in 0.12 seconds =========================
 
 Writing well integrated assertion helpers
 --------------------------------------------------
 
 .. regendoc:wipe
 
 If you have a test helper function called from a test you can
@@ -199,57 +211,63 @@ use the ``pytest.fail`` marker to fail a
 The test support function will not show up in the traceback if you
 set the ``__tracebackhide__`` option somewhere in the helper function.
 Example:
 
 .. code-block:: python
 
     # content of test_checkconfig.py
     import pytest
+
+
     def checkconfig(x):
         __tracebackhide__ = True
         if not hasattr(x, "config"):
-            pytest.fail("not configured: %s" %(x,))
+            pytest.fail("not configured: %s" % (x,))
+
 
     def test_something():
         checkconfig(42)
 
 The ``__tracebackhide__`` setting influences ``pytest`` showing
 of tracebacks: the ``checkconfig`` function will not be shown
 unless the ``--full-trace`` command line option is specified.
 Let's run our little function::
 
     $ pytest -q test_checkconfig.py
     F                                                                    [100%]
     ================================= FAILURES =================================
     ______________________________ test_something ______________________________
-    
+
         def test_something():
     >       checkconfig(42)
     E       Failed: not configured: 42
-    
-    test_checkconfig.py:8: Failed
+
+    test_checkconfig.py:11: Failed
     1 failed in 0.12 seconds
 
 If you only want to hide certain exceptions, you can set ``__tracebackhide__``
 to a callable which gets the ``ExceptionInfo`` object. You can for example use
 this to make sure unexpected exception types aren't hidden:
 
 .. code-block:: python
 
     import operator
     import pytest
 
+
     class ConfigException(Exception):
         pass
 
+
     def checkconfig(x):
-        __tracebackhide__ = operator.methodcaller('errisinstance', ConfigException)
+        __tracebackhide__ = operator.methodcaller("errisinstance", ConfigException)
         if not hasattr(x, "config"):
-            raise ConfigException("not configured: %s" %(x,))
+            raise ConfigException("not configured: %s" % (x,))
+
 
     def test_something():
         checkconfig(42)
 
 This will avoid hiding the exception traceback on unrelated exceptions (i.e.
 bugs in assertion helpers).
 
 
@@ -262,97 +280,105 @@ Usually it is a bad idea to make applica
 behave differently if called from a test.  But if you
 absolutely must find out if your application code is
 running from a test you can do something like this:
 
 .. code-block:: python
 
     # content of conftest.py
 
+
     def pytest_configure(config):
         import sys
+
         sys._called_from_test = True
 
+
     def pytest_unconfigure(config):
         import sys
+
         del sys._called_from_test
 
 and then check for the ``sys._called_from_test`` flag:
 
 .. code-block:: python
 
-    if hasattr(sys, '_called_from_test'):
+    if hasattr(sys, "_called_from_test"):
         # called from within a test run
+        ...
     else:
         # called "normally"
+        ...
 
 accordingly in your application.  It's also a good idea
 to use your own application module rather than ``sys``
 for handling flag.
 
 Adding info to test report header
 --------------------------------------------------------------
 
 .. regendoc:wipe
 
 It's easy to present extra information in a ``pytest`` run:
 
 .. code-block:: python
 
     # content of conftest.py
 
+
     def pytest_report_header(config):
         return "project deps: mylib-1.1"
 
 which will add the string to the test header accordingly::
 
     $ pytest
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     project deps: mylib-1.1
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 0 items
-    
+
     ======================= no tests ran in 0.12 seconds =======================
 
 .. regendoc:wipe
 
 It is also possible to return a list of strings which will be considered as several
 lines of information. You may consider ``config.getoption('verbose')`` in order to
 display more information if applicable:
 
 .. code-block:: python
 
     # content of conftest.py
 
+
     def pytest_report_header(config):
-        if config.getoption('verbose') > 0:
+        if config.getoption("verbose") > 0:
             return ["info1: did you know that ...", "did you?"]
 
 which will add info only when run with "--v"::
 
     $ pytest -v
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
-    cachedir: .cache
+    cachedir: .pytest_cache
     info1: did you know that ...
     did you?
     rootdir: $REGENDOC_TMPDIR, inifile:
     collecting ... collected 0 items
-    
+
     ======================= no tests ran in 0.12 seconds =======================
 
 and nothing when run plainly::
 
     $ pytest
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 0 items
-    
+
     ======================= no tests ran in 0.12 seconds =======================
 
 profiling test duration
 --------------------------
 
 .. regendoc:wipe
 
 .. versionadded: 2.2
@@ -360,35 +386,38 @@ profiling test duration
 If you have a slow running large test suite you might want to find
 out which tests are the slowest. Let's make an artificial test suite:
 
 .. code-block:: python
 
     # content of test_some_are_slow.py
     import time
 
+
     def test_funcfast():
         time.sleep(0.1)
 
+
     def test_funcslow1():
         time.sleep(0.2)
 
+
     def test_funcslow2():
         time.sleep(0.3)
 
 Now we can profile which test functions execute the slowest::
 
     $ pytest --durations=3
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 3 items
-    
+
     test_some_are_slow.py ...                                            [100%]
-    
+
     ========================= slowest 3 test durations =========================
     0.30s call     test_some_are_slow.py::test_funcslow2
     0.20s call     test_some_are_slow.py::test_funcslow1
     0.10s call     test_some_are_slow.py::test_funcfast
     ========================= 3 passed in 0.12 seconds =========================
 
 incremental testing - test steps
 ---------------------------------------------------
@@ -402,72 +431,78 @@ add no insight.  Here is a simple ``conf
 an ``incremental`` marker which is to be used on classes:
 
 .. code-block:: python
 
     # content of conftest.py
 
     import pytest
 
+
     def pytest_runtest_makereport(item, call):
         if "incremental" in item.keywords:
             if call.excinfo is not None:
                 parent = item.parent
                 parent._previousfailed = item
 
+
     def pytest_runtest_setup(item):
         if "incremental" in item.keywords:
             previousfailed = getattr(item.parent, "_previousfailed", None)
             if previousfailed is not None:
-                pytest.xfail("previous test failed (%s)" %previousfailed.name)
+                pytest.xfail("previous test failed (%s)" % previousfailed.name)
 
 These two hook implementations work together to abort incremental-marked
 tests in a class.  Here is a test module example:
 
 .. code-block:: python
 
     # content of test_step.py
 
     import pytest
 
+
     @pytest.mark.incremental
     class TestUserHandling(object):
         def test_login(self):
             pass
+
         def test_modification(self):
             assert 0
+
         def test_deletion(self):
             pass
 
+
     def test_normal():
         pass
 
 If we run this::
 
     $ pytest -rx
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 4 items
-    
+
     test_step.py .Fx.                                                    [100%]
+
+    ================================= FAILURES =================================
+    ____________________ TestUserHandling.test_modification ____________________
+
+    self = <test_step.TestUserHandling object at 0xdeadbeef>
+
+        def test_modification(self):
+    >       assert 0
+    E       assert 0
+
+    test_step.py:11: AssertionError
     ========================= short test summary info ==========================
     XFAIL test_step.py::TestUserHandling::()::test_deletion
       reason: previous test failed (test_modification)
-    
-    ================================= FAILURES =================================
-    ____________________ TestUserHandling.test_modification ____________________
-    
-    self = <test_step.TestUserHandling object at 0xdeadbeef>
-    
-        def test_modification(self):
-    >       assert 0
-    E       assert 0
-    
-    test_step.py:9: AssertionError
     ============== 1 failed, 2 passed, 1 xfailed in 0.12 seconds ===============
 
 We'll see that ``test_deletion`` was not executed because ``test_modification``
 failed.  It is reported as an "expected failure".
 
 
 Package/Directory-level fixtures (setups)
 -------------------------------------------------------
@@ -482,19 +517,21 @@ setup/teardown functions, especially if 
 
 Here is an example for making a ``db`` fixture available in a directory:
 
 .. code-block:: python
 
     # content of a/conftest.py
     import pytest
 
+
     class DB(object):
         pass
 
+
     @pytest.fixture(scope="session")
     def db():
         return DB()
 
 and then a test module in that directory:
 
 .. code-block:: python
 
@@ -521,60 +558,60 @@ the ``db`` fixture:
 
 We can run this::
 
     $ pytest
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 7 items
-    
+
     test_step.py .Fx.                                                    [ 57%]
     a/test_db.py F                                                       [ 71%]
     a/test_db2.py F                                                      [ 85%]
     b/test_error.py E                                                    [100%]
-    
+
     ================================== ERRORS ==================================
     _______________________ ERROR at setup of test_root ________________________
     file $REGENDOC_TMPDIR/b/test_error.py, line 1
       def test_root(db):  # no db here, will error out
     E       fixture 'db' not found
-    >       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_xml_property, recwarn, tmpdir, tmpdir_factory
+    >       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_xml_attribute, record_xml_property, recwarn, tmpdir, tmpdir_factory
     >       use 'pytest --fixtures [testpath]' for help on them.
-    
+
     $REGENDOC_TMPDIR/b/test_error.py:1
     ================================= FAILURES =================================
     ____________________ TestUserHandling.test_modification ____________________
-    
+
     self = <test_step.TestUserHandling object at 0xdeadbeef>
-    
+
         def test_modification(self):
     >       assert 0
     E       assert 0
-    
-    test_step.py:9: AssertionError
+
+    test_step.py:11: AssertionError
     _________________________________ test_a1 __________________________________
-    
+
     db = <conftest.DB object at 0xdeadbeef>
-    
+
         def test_a1(db):
     >       assert 0, db  # to show value
     E       AssertionError: <conftest.DB object at 0xdeadbeef>
     E       assert 0
-    
+
     a/test_db.py:2: AssertionError
     _________________________________ test_a2 __________________________________
-    
+
     db = <conftest.DB object at 0xdeadbeef>
-    
+
         def test_a2(db):
     >       assert 0, db  # to show value
     E       AssertionError: <conftest.DB object at 0xdeadbeef>
     E       assert 0
-    
+
     a/test_db2.py:2: AssertionError
     ========== 3 failed, 2 passed, 1 xfailed, 1 error in 0.12 seconds ==========
 
 The two test modules in the ``a`` directory see the same ``db`` fixture instance
 while the one test in the sister-directory ``b`` doesn't see it.  We could of course
 also define a ``db`` fixture in that sister directory's ``conftest.py`` file.
 Note that each fixture is only instantiated if there is a test actually needing
 it (unless you use "autouse" fixture which are always executed ahead of the first test
@@ -593,16 +630,17 @@ case we just write some information out 
 
 .. code-block:: python
 
     # content of conftest.py
 
     import pytest
     import os.path
 
+
     @pytest.hookimpl(tryfirst=True, hookwrapper=True)
     def pytest_runtest_makereport(item, call):
         # execute all other hooks to obtain the report object
         outcome = yield
         rep = outcome.get_result()
 
         # we only look at actual failing test calls, not setup/teardown
         if rep.when == "call" and rep.failed:
@@ -619,46 +657,48 @@ case we just write some information out 
 
 if you then have failing tests:
 
 .. code-block:: python
 
     # content of test_module.py
     def test_fail1(tmpdir):
         assert 0
+
+
     def test_fail2():
         assert 0
 
 and run them::
 
     $ pytest test_module.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 2 items
-    
+
     test_module.py FF                                                    [100%]
-    
+
     ================================= FAILURES =================================
     ________________________________ test_fail1 ________________________________
-    
+
     tmpdir = local('PYTEST_TMPDIR/test_fail10')
-    
+
         def test_fail1(tmpdir):
     >       assert 0
     E       assert 0
-    
+
     test_module.py:2: AssertionError
     ________________________________ test_fail2 ________________________________
-    
+
         def test_fail2():
     >       assert 0
     E       assert 0
-    
-    test_module.py:4: AssertionError
+
+    test_module.py:6: AssertionError
     ========================= 2 failed in 0.12 seconds =========================
 
 you will have a "failures" file which contains the failing test ids::
 
     $ cat failures
     test_module.py::test_fail1 (PYTEST_TMPDIR/test_fail10)
     test_module.py::test_fail2
 
@@ -671,16 +711,17 @@ If you want to make test result reports 
 here is a little example implemented via a local plugin:
 
 .. code-block:: python
 
     # content of conftest.py
 
     import pytest
 
+
     @pytest.hookimpl(tryfirst=True, hookwrapper=True)
     def pytest_runtest_makereport(item, call):
         # execute all other hooks to obtain the report object
         outcome = yield
         rep = outcome.get_result()
 
         # set a report attribute for each phase of a call, which can
         # be "setup", "call", "teardown"
@@ -689,106 +730,112 @@ here is a little example implemented via
 
 
     @pytest.fixture
     def something(request):
         yield
         # request.node is an "item" because we use the default
         # "function" scope
         if request.node.rep_setup.failed:
-            print ("setting up a test failed!", request.node.nodeid)
+            print("setting up a test failed!", request.node.nodeid)
         elif request.node.rep_setup.passed:
             if request.node.rep_call.failed:
-                print ("executing test failed", request.node.nodeid)
+                print("executing test failed", request.node.nodeid)
 
 
 if you then have failing tests:
 
 .. code-block:: python
 
     # content of test_module.py
 
     import pytest
 
+
     @pytest.fixture
     def other():
         assert 0
 
+
     def test_setup_fails(something, other):
         pass
 
+
     def test_call_fails(something):
         assert 0
 
+
     def test_fail2():
         assert 0
 
 and run it::
 
     $ pytest -s test_module.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 3 items
-    
+
     test_module.py Esetting up a test failed! test_module.py::test_setup_fails
     Fexecuting test failed test_module.py::test_call_fails
-    F                                                   [100%]
-    
+    F
+
     ================================== ERRORS ==================================
     ____________________ ERROR at setup of test_setup_fails ____________________
-    
+
         @pytest.fixture
         def other():
     >       assert 0
     E       assert 0
-    
-    test_module.py:6: AssertionError
+
+    test_module.py:7: AssertionError
     ================================= FAILURES =================================
     _____________________________ test_call_fails ______________________________
-    
+
     something = None
-    
+
         def test_call_fails(something):
     >       assert 0
     E       assert 0
-    
-    test_module.py:12: AssertionError
+
+    test_module.py:15: AssertionError
     ________________________________ test_fail2 ________________________________
-    
+
         def test_fail2():
     >       assert 0
     E       assert 0
-    
-    test_module.py:15: AssertionError
+
+    test_module.py:19: AssertionError
     ==================== 2 failed, 1 error in 0.12 seconds =====================
 
 You'll see that the fixture finalizers could use the precise reporting
 information.
 
+.. _pytest current test env:
+
 ``PYTEST_CURRENT_TEST`` environment variable
 --------------------------------------------
 
 .. versionadded:: 3.2
 
 Sometimes a test session might get stuck and there might be no easy way to figure out
 which test got stuck, for example if pytest was run in quiet mode (``-q``) or you don't have access to the console
 output. This is particularly a problem if the problem helps only sporadically, the famous "flaky" kind of tests.
 
 ``pytest`` sets a ``PYTEST_CURRENT_TEST`` environment variable when running tests, which can be inspected
-by process monitoring utilities or libraries like `psutil <https://pypi.python.org/pypi/psutil>`_ to discover which
+by process monitoring utilities or libraries like `psutil <https://pypi.org/project/psutil/>`_ to discover which
 test got stuck if necessary:
 
 .. code-block:: python
 
     import psutil
 
     for pid in psutil.pids():
         environ = psutil.Process(pid).environ()
-        if 'PYTEST_CURRENT_TEST' in environ:
+        if "PYTEST_CURRENT_TEST" in environ:
             print(f'pytest process {pid} running: {environ["PYTEST_CURRENT_TEST"]}')
 
 During the test session pytest will set ``PYTEST_CURRENT_TEST`` to the current test
 :ref:`nodeid <nodeids>` and the current stage, which can be ``setup``, ``call``
 and ``teardown``.
 
 For example, when running a single test function named ``test_foo`` from ``foo_module.py``,
 ``PYTEST_CURRENT_TEST`` will be set to:
@@ -800,46 +847,52 @@ For example, when running a single test 
 In that order.
 
 .. note::
 
     The contents of ``PYTEST_CURRENT_TEST`` is meant to be human readable and the actual format
     can be changed between releases (even bug fixes) so it shouldn't be relied on for scripting
     or automation.
 
-Freezing pytest 
+Freezing pytest
 ---------------
 
 If you freeze your application using a tool like
 `PyInstaller <https://pyinstaller.readthedocs.io>`_
 in order to distribute it to your end-users, it is a good idea to also package
 your test runner and run your tests using the frozen application. This way packaging
 errors such as dependencies not being included into the executable can be detected early
 while also allowing you to send test files to users so they can run them in their
 machines, which can be useful to obtain more information about a hard to reproduce bug.
 
 Fortunately recent ``PyInstaller`` releases already have a custom hook
-for pytest, but if you are using another tool to freeze executables 
+for pytest, but if you are using another tool to freeze executables
 such as ``cx_freeze`` or ``py2exe``, you can use ``pytest.freeze_includes()``
 to obtain the full list of internal pytest modules. How to configure the tools
 to find the internal modules varies from tool to tool, however.
 
-Instead of freezing the pytest runner as a separate executable, you can make 
+Instead of freezing the pytest runner as a separate executable, you can make
 your frozen program work as the pytest runner by some clever
-argument handling during program startup. This allows you to 
+argument handling during program startup. This allows you to
 have a single executable, which is usually more convenient.
+Please note that the mechanism for plugin discovery used by pytest
+(setupttools entry points) doesn't work with frozen executables so pytest
+can't find any third party plugins automatically. To include third party plugins
+like ``pytest-timeout`` they must be imported explicitly and passed on to pytest.main.
 
 .. code-block:: python
 
     # contents of app_main.py
     import sys
+    import pytest_timeout  # Third party plugin
 
-    if len(sys.argv) > 1 and sys.argv[1] == '--pytest':
+    if len(sys.argv) > 1 and sys.argv[1] == "--pytest":
         import pytest
-        sys.exit(pytest.main(sys.argv[2:]))
+
+        sys.exit(pytest.main(sys.argv[2:], plugins=[pytest_timeout]))
     else:
         # normal application execution: at this point argv can be parsed
         # by your argument-parsing library of choice as usual
         ...
 
 
 This allows you to execute tests using the frozen
 application with standard ``pytest`` command-line options::
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/special.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/special.rst
@@ -63,10 +63,10 @@ If you run this without output capturing
     callattr_ahead_of_alltests called
     callme called!
     callme other called
     SomeTest callme called
     test_method1 called
     .test_method1 called
     .test other
     .test_unit1 method called
-    .                                                                 [100%]
+    .
     4 passed in 0.12 seconds
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/xfail_demo.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/example/xfail_demo.py
@@ -1,30 +1,38 @@
 import pytest
+
 xfail = pytest.mark.xfail
 
+
 @xfail
 def test_hello():
     assert 0
 
+
 @xfail(run=False)
 def test_hello2():
     assert 0
 
+
 @xfail("hasattr(os, 'sep')")
 def test_hello3():
     assert 0
 
+
 @xfail(reason="bug 110")
 def test_hello4():
     assert 0
 
+
 @xfail('pytest.__version__[0] != "17"')
 def test_hello5():
     assert 0
 
+
 def test_hello6():
     pytest.xfail("reason")
 
+
 @xfail(raises=IndexError)
 def test_hello7():
     x = []
     x[1] = 1
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/faq.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/faq.rst
@@ -25,24 +25,24 @@ how does pytest relate to twisted's tria
 ++++++++++++++++++++++++++++++++++++++++++++++
 
 Since some time ``pytest`` has builtin support for supporting tests
 written using trial. It does not itself start a reactor, however,
 and does not handle Deferreds returned from a test in pytest style.
 If you are using trial's unittest.TestCase chances are that you can
 just run your tests even if you return Deferreds.  In addition,
 there also is a dedicated `pytest-twisted
-<http://pypi.python.org/pypi/pytest-twisted>`_ plugin which allows you to
+<https://pypi.org/project/pytest-twisted/>`_ plugin which allows you to
 return deferreds from pytest-style tests, allowing the use of
 :ref:`fixtures` and other features.
 
 how does pytest work with Django?
 ++++++++++++++++++++++++++++++++++++++++++++++
 
-In 2012, some work is going into the `pytest-django plugin <http://pypi.python.org/pypi/pytest-django>`_.  It substitutes the usage of Django's
+In 2012, some work is going into the `pytest-django plugin <https://pypi.org/project/pytest-django/>`_.  It substitutes the usage of Django's
 ``manage.py test`` and allows the use of all pytest features_ most of which
 are not available from Django directly.
 
 .. _features: features.html
 
 
 What's this "magic" with pytest? (historic notes)
 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/fixture.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/fixture.rst
@@ -68,30 +68,30 @@ Here, the ``test_ehlo`` needs the ``smtp
 will discover and call the :py:func:`@pytest.fixture <_pytest.python.fixture>`
 marked ``smtp`` fixture function.  Running the test looks like this::
 
     $ pytest test_smtpsimple.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 1 item
-    
+
     test_smtpsimple.py F                                                 [100%]
-    
+
     ================================= FAILURES =================================
     ________________________________ test_ehlo _________________________________
-    
+
     smtp = <smtplib.SMTP object at 0xdeadbeef>
-    
+
         def test_ehlo(smtp):
             response, msg = smtp.ehlo()
             assert response == 250
     >       assert 0 # for demo purposes
     E       assert 0
-    
+
     test_smtpsimple.py:11: AssertionError
     ========================= 1 failed in 0.12 seconds =========================
 
 In the failure traceback we see that the test function was called with a
 ``smtp`` argument, the ``smtplib.SMTP()`` instance created by the fixture
 function.  The test function fails on our deliberate ``assert 0``.  Here is
 the exact protocol used by ``pytest`` to call the test function this way:
 
@@ -106,21 +106,21 @@ 3. ``test_ehlo(<SMTP instance>)`` is cal
    line of the test function.
 
 Note that if you misspell a function argument or want
 to use one that isn't available, you'll see an error
 with a list of available function arguments.
 
 .. note::
 
-    You can always issue::
+    You can always issue ::
 
         pytest --fixtures test_simplefactory.py
 
-    to see available fixtures.
+    to see available fixtures (fixtures with leading ``_`` are only shown if you add the ``-v`` option).
 
 Fixtures: a prime example of dependency injection
 ---------------------------------------------------
 
 Fixtures allow test functions to easily receive and work
 against specific pre-initialized application objects without having
 to care about import/setup/cleanup details.
 It's a prime example of `dependency injection`_ where fixture
@@ -136,48 +136,48 @@ functions take the role of the *injector
 If during implementing your tests you realize that you
 want to use a fixture function from multiple test files you can move it
 to a ``conftest.py`` file.
 You don't need to import the fixture you want to use in a test, it
 automatically gets discovered by pytest. The discovery of
 fixture functions starts at test classes, then test modules, then
 ``conftest.py`` files and finally builtin and third party plugins.
 
-You can also use the ``conftest.py`` file to implement 
+You can also use the ``conftest.py`` file to implement
 :ref:`local per-directory plugins <conftest.py plugins>`.
 
 Sharing test data
 -----------------
 
 If you want to make test data from files available to your tests, a good way
 to do this is by loading these data in a fixture for use by your tests.
 This makes use of the automatic caching mechanisms of pytest.
 
 Another good approach is by adding the data files in the ``tests`` folder.
-There are also community plugins available to help managing this aspect of 
-testing, e.g. `pytest-datadir <https://github.com/gabrielcnr/pytest-datadir>`__ 
-and `pytest-datafiles <https://pypi.python.org/pypi/pytest-datafiles>`__. 
+There are also community plugins available to help managing this aspect of
+testing, e.g. `pytest-datadir <https://github.com/gabrielcnr/pytest-datadir>`__
+and `pytest-datafiles <https://pypi.python.org/pypi/pytest-datafiles>`__.
 
 .. _smtpshared:
 
 Scope: sharing a fixture instance across tests in a class, module or session
 ----------------------------------------------------------------------------
 
 .. regendoc:wipe
 
 Fixtures requiring network access depend on connectivity and are
 usually time-expensive to create.  Extending the previous example, we
-can add a ``scope='module'`` parameter to the
+can add a ``scope="module"`` parameter to the
 :py:func:`@pytest.fixture <_pytest.python.fixture>` invocation
 to cause the decorated ``smtp`` fixture function to only be invoked once
 per test *module* (the default is to invoke once per test *function*).
 Multiple test functions in a test module will thus
 each receive the same ``smtp`` fixture instance, thus saving time.
 
-The next example puts the fixture function into a separate ``conftest.py`` file 
+The next example puts the fixture function into a separate ``conftest.py`` file
 so that tests from multiple test modules in the directory can
 access the fixture function::
 
     # content of conftest.py
     import pytest
     import smtplib
 
     @pytest.fixture(scope="module")
@@ -204,95 +204,145 @@ function (in or below the directory wher
 We deliberately insert failing ``assert 0`` statements in order to
 inspect what is going on and can now run the tests::
 
     $ pytest test_module.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 2 items
-    
+
     test_module.py FF                                                    [100%]
-    
+
     ================================= FAILURES =================================
     ________________________________ test_ehlo _________________________________
-    
+
     smtp = <smtplib.SMTP object at 0xdeadbeef>
-    
+
         def test_ehlo(smtp):
             response, msg = smtp.ehlo()
             assert response == 250
             assert b"smtp.gmail.com" in msg
     >       assert 0  # for demo purposes
     E       assert 0
-    
+
     test_module.py:6: AssertionError
     ________________________________ test_noop _________________________________
-    
+
     smtp = <smtplib.SMTP object at 0xdeadbeef>
-    
+
         def test_noop(smtp):
             response, msg = smtp.noop()
             assert response == 250
     >       assert 0  # for demo purposes
     E       assert 0
-    
+
     test_module.py:11: AssertionError
     ========================= 2 failed in 0.12 seconds =========================
 
 You see the two ``assert 0`` failing and more importantly you can also see
 that the same (module-scoped) ``smtp`` object was passed into the two
 test functions because pytest shows the incoming argument values in the
 traceback.  As a result, the two test functions using ``smtp`` run as
 quick as a single one because they reuse the same instance.
 
 If you decide that you rather want to have a session-scoped ``smtp``
 instance, you can simply declare it:
 
 .. code-block:: python
 
     @pytest.fixture(scope="session")
-    def smtp(...):
+    def smtp():
         # the returned fixture value will be shared for
         # all tests needing it
+        ...
 
 Finally, the ``class`` scope will invoke the fixture once per test *class*.
 
+
+Higher-scoped fixtures are instantiated first
+---------------------------------------------
+
+.. versionadded:: 3.5
+
+Within a function request for features, fixture of higher-scopes (such as ``session``) are instantiated first than
+lower-scoped fixtures (such as ``function`` or ``class``). The relative order of fixtures of same scope follows
+the declared order in the test function and honours dependencies between fixtures.
+
+Consider the code below:
+
+.. code-block:: python
+
+    @pytest.fixture(scope="session")
+    def s1():
+        pass
+
+
+    @pytest.fixture(scope="module")
+    def m1():
+        pass
+
+
+    @pytest.fixture
+    def f1(tmpdir):
+        pass
+
+
+    @pytest.fixture
+    def f2():
+        pass
+
+
+    def test_foo(f1, m1, f2, s1):
+        ...
+
+
+The fixtures requested by ``test_foo`` will be instantiated in the following order:
+
+1. ``s1``: is the highest-scoped fixture (``session``).
+2. ``m1``: is the second highest-scoped fixture (``module``).
+3. ``tmpdir``: is a ``function``-scoped fixture, required by ``f1``: it needs to be instantiated at this point
+   because it is a dependency of ``f1``.
+4. ``f1``: is the first ``function``-scoped fixture in ``test_foo`` parameter list.
+5. ``f2``: is the last ``function``-scoped fixture in ``test_foo`` parameter list.
+
+
 .. _`finalization`:
 
 Fixture finalization / executing teardown code
 -------------------------------------------------------------
 
 pytest supports execution of fixture specific finalization code
 when the fixture goes out of scope.  By using a ``yield`` statement instead of ``return``, all
 the code after the *yield* statement serves as the teardown code:
 
 .. code-block:: python
 
     # content of conftest.py
 
     import smtplib
     import pytest
 
+
     @pytest.fixture(scope="module")
     def smtp():
         smtp = smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
         yield smtp  # provide the fixture value
         print("teardown smtp")
         smtp.close()
 
 The ``print`` and ``smtp.close()`` statements will execute when the last test in
 the module has finished execution, regardless of the exception status of the
 tests.
 
 Let's execute it::
 
     $ pytest -s -q --tb=no
-    FF                                                                   [100%]teardown smtp
-    
+    FFteardown smtp
+
     2 failed in 0.12 seconds
 
 We see that the ``smtp`` instance is finalized after the two
 tests finished execution.  Note that if we decorated our fixture
 function with ``scope='function'`` then fixture setup and cleanup would
 occur around each single test.  In either case the test
 module itself does not need to change or know about these details
 of fixture setup.
@@ -301,16 +351,17 @@ Note that we can also seamlessly use the
 
 .. code-block:: python
 
     # content of test_yield2.py
 
     import smtplib
     import pytest
 
+
     @pytest.fixture(scope="module")
     def smtp():
         with smtplib.SMTP("smtp.gmail.com", 587, timeout=5) as smtp:
             yield smtp  # provide the fixture value
 
 
 The ``smtp`` connection will be closed after the test finished execution
 because the ``smtp`` object automatically closes when
@@ -326,22 +377,25 @@ finalization functions.
 Here's the ``smtp`` fixture changed to use ``addfinalizer`` for cleanup:
 
 .. code-block:: python
 
     # content of conftest.py
     import smtplib
     import pytest
 
+
     @pytest.fixture(scope="module")
     def smtp(request):
         smtp = smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
+
         def fin():
-            print ("teardown smtp")
+            print("teardown smtp")
             smtp.close()
+
         request.addfinalizer(fin)
         return smtp  # provide the fixture value
 
 
 Both ``yield`` and ``addfinalizer`` methods work similarly by calling their code after the test
 ends, but ``addfinalizer`` has two key differences over ``yield``:
 
 1. It is possible to register multiple finalizer functions.
@@ -364,17 +418,17 @@ 2. Finalizers will always be called rega
    registered then it will not be executed.
 
 
 .. _`request-context`:
 
 Fixtures can introspect the requesting test context
 -------------------------------------------------------------
 
-Fixture function can accept the :py:class:`request <FixtureRequest>` object
+Fixture functions can accept the :py:class:`request <FixtureRequest>` object
 to introspect the "requesting" test function, class or module context.
 Further extending the previous ``smtp`` fixture example, let's
 read an optional server URL from the test module which uses our fixture::
 
     # content of conftest.py
     import pytest
     import smtplib
 
@@ -386,18 +440,18 @@ read an optional server URL from the tes
         print ("finalizing %s (%s)" % (smtp, server))
         smtp.close()
 
 We use the ``request.module`` attribute to optionally obtain an
 ``smtpserver`` attribute from the test module.  If we just execute
 again, nothing much has changed::
 
     $ pytest -s -q --tb=no
-    FF                                                                   [100%]finalizing <smtplib.SMTP object at 0xdeadbeef> (smtp.gmail.com)
-    
+    FFfinalizing <smtplib.SMTP object at 0xdeadbeef> (smtp.gmail.com)
+
     2 failed in 0.12 seconds
 
 Let's quickly create another test module that actually sets the
 server URL in its module namespace::
 
     # content of test_anothersmtp.py
 
     smtpserver = "mail.python.org"  # will be read by smtp fixture
@@ -416,16 +470,69 @@ Running it::
     E   AssertionError: (250, b'mail.python.org')
     E   assert 0
     ------------------------- Captured stdout teardown -------------------------
     finalizing <smtplib.SMTP object at 0xdeadbeef> (mail.python.org)
 
 voila! The ``smtp`` fixture function picked up our mail server name
 from the module namespace.
 
+.. _`fixture-factory`:
+
+Factories as fixtures
+-------------------------------------------------------------
+
+The "factory as fixture" pattern can help in situations where the result
+of a fixture is needed multiple times in a single test. Instead of returning
+data directly, the fixture instead returns a function which generates the data.
+This function can then be called multiple times in the test.
+
+Factories can have have parameters as needed::
+
+    @pytest.fixture
+    def make_customer_record():
+
+        def _make_customer_record(name):
+            return {
+                "name": name,
+                "orders": []
+            }
+
+        return _make_customer_record
+
+
+    def test_customer_records(make_customer_record):
+        customer_1 = make_customer_record("Lisa")
+        customer_2 = make_customer_record("Mike")
+        customer_3 = make_customer_record("Meredith")
+
+If the data created by the factory requires managing, the fixture can take care of that::
+
+    @pytest.fixture
+    def make_customer_record():
+
+        created_records = []
+
+        def _make_customer_record(name):
+            record = models.Customer(name=name, orders=[])
+            created_records.append(record)
+            return record
+
+        yield _make_customer_record
+
+        for record in created_records:
+            record.destroy()
+
+
+    def test_customer_records(make_customer_record):
+        customer_1 = make_customer_record("Lisa")
+        customer_2 = make_customer_record("Mike")
+        customer_3 = make_customer_record("Meredith")
+
+
 .. _`fixture-parametrize`:
 
 Parametrizing fixtures
 -----------------------------------------------------------------
 
 Fixture functions can be parametrized in which case they will be called
 multiple times, each time executing the set of dependent tests, i. e. the
 tests that depend on this fixture.  Test functions do usually not need
@@ -455,61 +562,61 @@ The main change is the declaration of ``
 for each of which the fixture function will execute and can access
 a value via ``request.param``.  No test function code needs to change.
 So let's just do another run::
 
     $ pytest -q test_module.py
     FFFF                                                                 [100%]
     ================================= FAILURES =================================
     ________________________ test_ehlo[smtp.gmail.com] _________________________
-    
+
     smtp = <smtplib.SMTP object at 0xdeadbeef>
-    
+
         def test_ehlo(smtp):
             response, msg = smtp.ehlo()
             assert response == 250
             assert b"smtp.gmail.com" in msg
     >       assert 0  # for demo purposes
     E       assert 0
-    
+
     test_module.py:6: AssertionError
     ________________________ test_noop[smtp.gmail.com] _________________________
-    
+
     smtp = <smtplib.SMTP object at 0xdeadbeef>
-    
+
         def test_noop(smtp):
             response, msg = smtp.noop()
             assert response == 250
     >       assert 0  # for demo purposes
     E       assert 0
-    
+
     test_module.py:11: AssertionError
     ________________________ test_ehlo[mail.python.org] ________________________
-    
+
     smtp = <smtplib.SMTP object at 0xdeadbeef>
-    
+
         def test_ehlo(smtp):
             response, msg = smtp.ehlo()
             assert response == 250
     >       assert b"smtp.gmail.com" in msg
     E       AssertionError: assert b'smtp.gmail.com' in b'mail.python.org\nPIPELINING\nSIZE 51200000\nETRN\nSTARTTLS\nAUTH DIGEST-MD5 NTLM CRAM-MD5\nENHANCEDSTATUSCODES\n8BITMIME\nDSN\nSMTPUTF8'
-    
+
     test_module.py:5: AssertionError
     -------------------------- Captured stdout setup ---------------------------
     finalizing <smtplib.SMTP object at 0xdeadbeef>
     ________________________ test_noop[mail.python.org] ________________________
-    
+
     smtp = <smtplib.SMTP object at 0xdeadbeef>
-    
+
         def test_noop(smtp):
             response, msg = smtp.noop()
             assert response == 250
     >       assert 0  # for demo purposes
     E       assert 0
-    
+
     test_module.py:11: AssertionError
     ------------------------- Captured stdout teardown -------------------------
     finalizing <smtplib.SMTP object at 0xdeadbeef>
     4 failed in 0.12 seconds
 
 We see that our two test functions each ran twice, against the different
 ``smtp`` instances.  Note also, that with the ``mail.python.org``
 connection the second test fails in ``test_ehlo`` because a
@@ -571,19 +678,53 @@ Running the above tests results in the f
      <Function 'test_a[ham]'>
      <Function 'test_b[eggs]'>
      <Function 'test_b[1]'>
    <Module 'test_module.py'>
      <Function 'test_ehlo[smtp.gmail.com]'>
      <Function 'test_noop[smtp.gmail.com]'>
      <Function 'test_ehlo[mail.python.org]'>
      <Function 'test_noop[mail.python.org]'>
-   
+
    ======================= no tests ran in 0.12 seconds =======================
 
+.. _`fixture-parametrize-marks`:
+
+Using marks with parametrized fixtures
+--------------------------------------
+
+:func:`pytest.param` can be used to apply marks in values sets of parametrized fixtures in the same way
+that they can be used with :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>`.
+
+Example::
+
+    # content of test_fixture_marks.py
+    import pytest
+    @pytest.fixture(params=[0, 1, pytest.param(2, marks=pytest.mark.skip)])
+    def data_set(request):
+        return request.param
+
+    def test_data(data_set):
+        pass
+
+Running this test will *skip* the invocation of ``data_set`` with value ``2``::
+
+    $ pytest test_fixture_marks.py -v
+    =========================== test session starts ============================
+    platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
+    cachedir: .pytest_cache
+    rootdir: $REGENDOC_TMPDIR, inifile:
+    collecting ... collected 3 items
+
+    test_fixture_marks.py::test_data[0] PASSED                           [ 33%]
+    test_fixture_marks.py::test_data[1] PASSED                           [ 66%]
+    test_fixture_marks.py::test_data[2] SKIPPED                          [100%]
+
+    =================== 2 passed, 1 skipped in 0.12 seconds ====================
+
 .. _`interdependent fixtures`:
 
 Modularity: using fixtures from a fixture function
 ----------------------------------------------------------
 
 You can not only use fixtures in test functions but fixture functions
 can use other fixtures themselves.  This contributes to a modular design
 of your fixtures and allows re-use of framework-specific fixtures across
@@ -607,23 +748,23 @@ and instantiate an object ``app`` where 
         assert app.smtp
 
 Here we declare an ``app`` fixture which receives the previously defined
 ``smtp`` fixture and instantiates an ``App`` object with it.  Let's run it::
 
     $ pytest -v test_appsetup.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
-    cachedir: .cache
+    cachedir: .pytest_cache
     rootdir: $REGENDOC_TMPDIR, inifile:
     collecting ... collected 2 items
-    
+
     test_appsetup.py::test_smtp_exists[smtp.gmail.com] PASSED            [ 50%]
     test_appsetup.py::test_smtp_exists[mail.python.org] PASSED           [100%]
-    
+
     ========================= 2 passed in 0.12 seconds =========================
 
 Due to the parametrization of ``smtp`` the test will run twice with two
 different ``App`` instances and respective smtp servers.  There is no
 need for the ``app`` fixture to be aware of the ``smtp`` parametrization
 as pytest will fully analyse the fixture dependency graph.
 
 Note, that the ``app`` fixture has a scope of ``module`` and uses a
@@ -676,53 +817,53 @@ to show the setup/teardown flow::
         print ("  RUN test2 with otherarg %s and modarg %s" % (otherarg, modarg))
 
 
 Let's run the tests in verbose mode and with looking at the print-output::
 
     $ pytest -v -s test_module.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python3.5
-    cachedir: .cache
+    cachedir: .pytest_cache
     rootdir: $REGENDOC_TMPDIR, inifile:
     collecting ... collected 8 items
-    
+
     test_module.py::test_0[1]   SETUP otherarg 1
       RUN test0 with otherarg 1
-    PASSED                                     [ 12%]  TEARDOWN otherarg 1
-    
+    PASSED  TEARDOWN otherarg 1
+
     test_module.py::test_0[2]   SETUP otherarg 2
       RUN test0 with otherarg 2
-    PASSED                                     [ 25%]  TEARDOWN otherarg 2
-    
+    PASSED  TEARDOWN otherarg 2
+
     test_module.py::test_1[mod1]   SETUP modarg mod1
       RUN test1 with modarg mod1
-    PASSED                                  [ 37%]
-    test_module.py::test_2[1-mod1]   SETUP otherarg 1
+    PASSED
+    test_module.py::test_2[mod1-1]   SETUP otherarg 1
       RUN test2 with otherarg 1 and modarg mod1
-    PASSED                                [ 50%]  TEARDOWN otherarg 1
-    
-    test_module.py::test_2[2-mod1]   SETUP otherarg 2
+    PASSED  TEARDOWN otherarg 1
+
+    test_module.py::test_2[mod1-2]   SETUP otherarg 2
       RUN test2 with otherarg 2 and modarg mod1
-    PASSED                                [ 62%]  TEARDOWN otherarg 2
-    
+    PASSED  TEARDOWN otherarg 2
+
     test_module.py::test_1[mod2]   TEARDOWN modarg mod1
       SETUP modarg mod2
       RUN test1 with modarg mod2
-    PASSED                                  [ 75%]
-    test_module.py::test_2[1-mod2]   SETUP otherarg 1
+    PASSED
+    test_module.py::test_2[mod2-1]   SETUP otherarg 1
       RUN test2 with otherarg 1 and modarg mod2
-    PASSED                                [ 87%]  TEARDOWN otherarg 1
-    
-    test_module.py::test_2[2-mod2]   SETUP otherarg 2
+    PASSED  TEARDOWN otherarg 1
+
+    test_module.py::test_2[mod2-2]   SETUP otherarg 2
       RUN test2 with otherarg 2 and modarg mod2
-    PASSED                                [100%]  TEARDOWN otherarg 2
+    PASSED  TEARDOWN otherarg 2
       TEARDOWN modarg mod2
-    
-    
+
+
     ========================= 8 passed in 0.12 seconds =========================
 
 You can see that the parametrized module-scoped ``modarg`` resource caused an
 ordering of test execution that lead to the fewest possible "active" resources.
 The finalizer for the ``mod1`` parametrized resource was executed before the
 ``mod2`` resource was setup.
 
 In particular notice that test_0 is completely independent and finishes first.
@@ -784,16 +925,18 @@ to verify our fixture is activated and t
     ..                                                                   [100%]
     2 passed in 0.12 seconds
 
 You can specify multiple fixtures like this:
 
 .. code-block:: python
 
     @pytest.mark.usefixtures("cleandir", "anotherfixture")
+    def test():
+        ...
 
 and you may specify fixture usage at the test module level, using
 a generic feature of the mark mechanism:
 
 .. code-block:: python
 
     pytestmark = pytest.mark.usefixtures("cleandir")
 
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/funcarg_compare.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/funcarg_compare.rst
@@ -1,109 +1,109 @@
 :orphan:
 
 .. _`funcargcompare`:
 
 pytest-2.3: reasoning for fixture/funcarg evolution
 =============================================================
 
-**Target audience**: Reading this document requires basic knowledge of 
-python testing, xUnit setup methods and the (previous) basic pytest 
-funcarg mechanism, see http://pytest.org/2.2.4/funcargs.html 
+**Target audience**: Reading this document requires basic knowledge of
+python testing, xUnit setup methods and the (previous) basic pytest
+funcarg mechanism, see http://pytest.org/2.2.4/funcargs.html
 If you are new to pytest, then you can simply ignore this
 section and read the other sections.
 
 .. currentmodule:: _pytest
 
 Shortcomings of the previous ``pytest_funcarg__`` mechanism
 --------------------------------------------------------------
 
 The pre pytest-2.3 funcarg mechanism calls a factory each time a
 funcarg for a test function is required.  If a factory wants to
-re-use a resource across different scopes, it often used 
-the ``request.cached_setup()`` helper to manage caching of 
-resources.  Here is a basic example how we could implement 
+re-use a resource across different scopes, it often used
+the ``request.cached_setup()`` helper to manage caching of
+resources.  Here is a basic example how we could implement
 a per-session Database object::
 
-    # content of conftest.py 
+    # content of conftest.py
     class Database(object):
         def __init__(self):
             print ("database instance created")
         def destroy(self):
             print ("database instance destroyed")
 
     def pytest_funcarg__db(request):
-        return request.cached_setup(setup=DataBase, 
+        return request.cached_setup(setup=DataBase,
                                     teardown=lambda db: db.destroy,
                                     scope="session")
 
 There are several limitations and difficulties with this approach:
 
 1. Scoping funcarg resource creation is not straight forward, instead one must
    understand the intricate cached_setup() method mechanics.
 
-2. parametrizing the "db" resource is not straight forward: 
+2. parametrizing the "db" resource is not straight forward:
    you need to apply a "parametrize" decorator or implement a
-   :py:func:`~hookspec.pytest_generate_tests` hook 
+   :py:func:`~hookspec.pytest_generate_tests` hook
    calling :py:func:`~python.Metafunc.parametrize` which
-   performs parametrization at the places where the resource 
-   is used.  Moreover, you need to modify the factory to use an 
-   ``extrakey`` parameter containing ``request.param`` to the 
+   performs parametrization at the places where the resource
+   is used.  Moreover, you need to modify the factory to use an
+   ``extrakey`` parameter containing ``request.param`` to the
    :py:func:`~python.Request.cached_setup` call.
 
 3. Multiple parametrized session-scoped resources will be active
    at the same time, making it hard for them to affect global state
    of the application under test.
 
 4. there is no way how you can make use of funcarg factories
    in xUnit setup methods.
 
-5. A non-parametrized fixture function cannot use a parametrized 
+5. A non-parametrized fixture function cannot use a parametrized
    funcarg resource if it isn't stated in the test function signature.
 
 All of these limitations are addressed with pytest-2.3 and its
 improved :ref:`fixture mechanism <fixture>`.
 
 
 Direct scoping of fixture/funcarg factories
 --------------------------------------------------------
 
 Instead of calling cached_setup() with a cache scope, you can use the
 :ref:`@pytest.fixture <pytest.fixture>` decorator and directly state
 the scope::
 
     @pytest.fixture(scope="session")
     def db(request):
-        # factory will only be invoked once per session - 
+        # factory will only be invoked once per session -
         db = DataBase()
         request.addfinalizer(db.destroy)  # destroy when session is finished
         return db
 
 This factory implementation does not need to call ``cached_setup()`` anymore
-because it will only be invoked once per session.  Moreover, the 
+because it will only be invoked once per session.  Moreover, the
 ``request.addfinalizer()`` registers a finalizer according to the specified
 resource scope on which the factory function is operating.
 
 
-Direct parametrization of funcarg resource factories 
+Direct parametrization of funcarg resource factories
 ----------------------------------------------------------
 
 Previously, funcarg factories could not directly cause parametrization.
 You needed to specify a ``@parametrize`` decorator on your test function
 or implement a ``pytest_generate_tests`` hook to perform
 parametrization, i.e. calling a test multiple times with different value
 sets.  pytest-2.3 introduces a decorator for use on the factory itself::
 
     @pytest.fixture(params=["mysql", "pg"])
     def db(request):
         ... # use request.param
 
-Here the factory will be invoked twice (with the respective "mysql" 
-and "pg" values set as ``request.param`` attributes) and all of 
-the tests requiring "db" will run twice as well.  The "mysql" and 
+Here the factory will be invoked twice (with the respective "mysql"
+and "pg" values set as ``request.param`` attributes) and all of
+the tests requiring "db" will run twice as well.  The "mysql" and
 "pg" values will also be used for reporting the test-invocation variants.
 
 This new way of parametrizing funcarg factories should in many cases
 allow to re-use already written factories because effectively
 ``request.param`` was already used when test functions/classes were
 parametrized via
 :py:func:`~_pytest.python.Metafunc.parametrize(indirect=True)` calls.
 
@@ -131,17 +131,17 @@ denotes the name under which the resourc
 argument::
 
     @pytest.fixture()
     def db(request):
         ...
 
 The name under which the funcarg resource can be requested is ``db``.
 
-You can still use the "old" non-decorator way of specifying funcarg factories 
+You can still use the "old" non-decorator way of specifying funcarg factories
 aka::
 
     def pytest_funcarg__db(request):
         ...
 
 
 But it is then not possible to define scoping and parametrization.
 It is thus recommended to use the factory decorator.
@@ -151,20 +151,20 @@ solving per-session setup / autouse fixt
 --------------------------------------------------------------
 
 pytest for a long time offered a pytest_configure and a pytest_sessionstart
 hook which are often used to setup global resources.  This suffers from
 several problems:
 
 1. in distributed testing the master process would setup test resources
    that are never needed because it only co-ordinates the test run
-   activities of the slave processes.  
+   activities of the slave processes.
 
-2. if you only perform a collection (with "--collect-only") 
-   resource-setup will still be executed.  
+2. if you only perform a collection (with "--collect-only")
+   resource-setup will still be executed.
 
 3. If a pytest_sessionstart is contained in some subdirectories
    conftest.py file, it will not be called.  This stems from the
    fact that this hook is actually used for reporting, in particular
    the test-header with platform/custom information.
 
 Moreover, it was not easy to define a scoped setup from plugins or
 conftest files other than to implement a ``pytest_runtest_setup()`` hook
@@ -189,30 +189,28 @@ overview of fixture management in your p
 
 .. _`compatibility notes`:
 
 .. _`funcargscompat`:
 
 Conclusion and compatibility notes
 ---------------------------------------------------------
 
-**funcargs** were originally introduced to pytest-2.0.  In pytest-2.3 
+**funcargs** were originally introduced to pytest-2.0.  In pytest-2.3
 the mechanism was extended and refined and is now described as
 fixtures:
 
-* previously funcarg factories were specified with a special 
-  ``pytest_funcarg__NAME`` prefix instead of using the 
+* previously funcarg factories were specified with a special
+  ``pytest_funcarg__NAME`` prefix instead of using the
   ``@pytest.fixture`` decorator.
 
 * Factories received a ``request`` object which managed caching through
-  ``request.cached_setup()`` calls and allowed using other funcargs via 
-  ``request.getfuncargvalue()`` calls.  These intricate APIs made it hard 
+  ``request.cached_setup()`` calls and allowed using other funcargs via
+  ``request.getfuncargvalue()`` calls.  These intricate APIs made it hard
   to do proper parametrization and implement resource caching. The
   new :py:func:`pytest.fixture` decorator allows to declare the scope
   and let pytest figure things out for you.
 
 * if you used parametrization and funcarg factories which made use of
   ``request.cached_setup()`` it is recommended to invest a few minutes
   and simplify your fixture function code to use the :ref:`@pytest.fixture`
-  decorator instead.  This will also allow to take advantage of 
+  decorator instead.  This will also allow to take advantage of
   the automatic per-resource grouping of tests.
-
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/funcargs.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/funcargs.rst
@@ -6,9 +6,8 @@ funcargs: resource injection and paramet
 pytest-2.3 introduces major refinements to fixture management
 of which the funcarg mechanism introduced with pytest-2.0 remains
 a core part.  The documentation has been refactored as well
 and you can read on here:
 
 - :ref:`fixtures`
 - :ref:`parametrize`
 - :ref:`funcargcompare`
-
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/genapi.py
+++ /dev/null
@@ -1,41 +0,0 @@
-import textwrap
-import inspect
-
-class Writer(object):
-    def __init__(self, clsname):
-        self.clsname = clsname
-
-    def __enter__(self):
-        self.file = open("%s.api" % self.clsname, "w")
-        return self
-
-    def __exit__(self, *args):
-        self.file.close()
-        print "wrote", self.file.name
-
-    def line(self, line):
-        self.file.write(line+"\n")
-
-    def docmethod(self, method):
-        doc = " ".join(method.__doc__.split())
-        indent = "         "
-        w = textwrap.TextWrapper(initial_indent=indent,
-                                 subsequent_indent=indent)
-
-        spec = inspect.getargspec(method)
-        del spec.args[0]
-        self.line(".. py:method:: " + method.__name__ +
-                  inspect.formatargspec(*spec))
-        self.line("")
-        self.line(w.fill(doc))
-        self.line("")
-
-def pytest_funcarg__a(request):
-    with Writer("request") as writer:
-        writer.docmethod(request.getfixturevalue)
-        writer.docmethod(request.cached_setup)
-        writer.docmethod(request.addfinalizer)
-        writer.docmethod(request.applymarker)
-
-def test_hello(a):
-    pass
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/getting-started.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/getting-started.rst
@@ -1,198 +1,183 @@
 Installation and Getting Started
 ===================================
 
 **Pythons**: Python 2.7, 3.4, 3.5, 3.6, Jython, PyPy-2.3
 
 **Platforms**: Unix/Posix and Windows
 
-**PyPI package name**: `pytest <http://pypi.python.org/pypi/pytest>`_
+**PyPI package name**: `pytest <https://pypi.org/project/pytest/>`_
 
-**dependencies**: `py <http://pypi.python.org/pypi/py>`_,
-`colorama (Windows) <http://pypi.python.org/pypi/colorama>`_,
+**Dependencies**: `py <https://pypi.org/project/py/>`_,
+`colorama (Windows) <https://pypi.org/project/colorama/>`_,
 
-**documentation as PDF**: `download latest <https://media.readthedocs.org/pdf/pytest/latest/pytest.pdf>`_
+**Documentation as PDF**: `download latest <https://media.readthedocs.org/pdf/pytest/latest/pytest.pdf>`_
+
+``pytest`` is a framework that makes building simple and scalable tests easy. Tests are expressive and readable—no boilerplate code required. Get started in minutes with a small unit test or complex functional test for your application or library.
 
 .. _`getstarted`:
-.. _installation:
+.. _`installation`:
 
-Installation
+Install ``pytest``
 ----------------------------------------
 
-Installation::
+1. Run the following command in your command line::
 
     pip install -U pytest
 
-To check your installation has installed the correct version::
+2. Check that you installed the correct version::
 
     $ pytest --version
     This is pytest version 3.x.y, imported from $PYTHON_PREFIX/lib/python3.5/site-packages/pytest.py
 
 .. _`simpletest`:
 
-Our first test run
+Create your first test
 ----------------------------------------------------------
 
-Let's create a first test file with a simple test function::
+Create a simple test function with just four lines of code::
 
     # content of test_sample.py
     def func(x):
         return x + 1
 
     def test_answer():
         assert func(3) == 5
 
-That's it. You can execute the test function now::
+That’s it. You can now execute the test function::
 
     $ pytest
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 1 item
-    
+
     test_sample.py F                                                     [100%]
-    
+
     ================================= FAILURES =================================
     _______________________________ test_answer ________________________________
-    
+
         def test_answer():
     >       assert func(3) == 5
     E       assert 4 == 5
     E        +  where 4 = func(3)
-    
+
     test_sample.py:5: AssertionError
     ========================= 1 failed in 0.12 seconds =========================
 
-We got a failure report because our little ``func(3)`` call did not return ``5``.
+This test returns a failure report because ``func(3)`` does not return ``5``.
 
 .. note::
 
-    You can simply use the ``assert`` statement for asserting test
-    expectations.  pytest's :ref:`assert introspection` will intelligently
-    report intermediate values of the assert expression freeing
-    you from the need to learn the many names of `JUnit legacy methods`_.
+    You can use the ``assert`` statement to verify test expectations. pytest’s `Advanced assertion introspection <http://docs.python.org/reference/simple_stmts.html#the-assert-statement>`_ will intelligently report intermediate values of the assert expression so you can avoid the many names `of JUnit legacy methods <http://docs.python.org/library/unittest.html#test-cases>`_.
 
-.. _`JUnit legacy methods`: http://docs.python.org/library/unittest.html#test-cases
-
-.. _`assert statement`: http://docs.python.org/reference/simple_stmts.html#the-assert-statement
-
-Running multiple tests
+Run multiple tests
 ----------------------------------------------------------
 
-``pytest`` will run all files in the current directory and its subdirectories of the form test_*.py or \*_test.py. More generally, it follows :ref:`standard test discovery rules <test discovery>`.
+``pytest`` will run all files of the form test_*.py or \*_test.py in the current directory and its subdirectories. More generally, it follows :ref:`standard test discovery rules <test discovery>`.
 
 
-Asserting that a certain exception is raised
+Assert that a certain exception is raised
 --------------------------------------------------------------
 
-If you want to assert that some code raises an exception you can
-use the ``raises`` helper::
+Use the ``raises`` helper to assert that some code raises an exception::
 
     # content of test_sysexit.py
     import pytest
     def f():
         raise SystemExit(1)
 
     def test_mytest():
         with pytest.raises(SystemExit):
             f()
 
-Running it with, this time in "quiet" reporting mode::
+Execute the test function with “quiet” reporting mode::
 
     $ pytest -q test_sysexit.py
     .                                                                    [100%]
     1 passed in 0.12 seconds
 
-Grouping multiple tests in a class
+Group multiple tests in a class
 --------------------------------------------------------------
 
-Once you start to have more than a few tests it often makes sense
-to group tests logically, in classes and modules.  Let's write a class
-containing two tests::
+Once you develop multiple tests, you may want to group them into a class. pytest makes it easy to create a class containing more than one test::
 
     # content of test_class.py
     class TestClass(object):
         def test_one(self):
             x = "this"
             assert 'h' in x
 
         def test_two(self):
             x = "hello"
             assert hasattr(x, 'check')
 
-The two tests are found because of the standard :ref:`test discovery`.
-There is no need to subclass anything.  We can simply
-run the module by passing its filename::
+``pytest`` discovers all tests following its :ref:`Conventions for Python test discovery <test discovery>`, so it finds both ``test_`` prefixed functions. There is no need to subclass anything. We can simply run the module by passing its filename::
 
     $ pytest -q test_class.py
     .F                                                                   [100%]
     ================================= FAILURES =================================
     ____________________________ TestClass.test_two ____________________________
-    
+
     self = <test_class.TestClass object at 0xdeadbeef>
-    
+
         def test_two(self):
             x = "hello"
     >       assert hasattr(x, 'check')
     E       AssertionError: assert False
     E        +  where False = hasattr('hello', 'check')
-    
+
     test_class.py:8: AssertionError
     1 failed, 1 passed in 0.12 seconds
 
-The first test passed, the second failed. Again we can easily see
-the intermediate values used in the assertion, helping us to
-understand the reason for the failure.
+The first test passed and the second failed. You can easily see the intermediate values in the assertion to help you understand the reason for the failure.
 
-Going functional: requesting a unique temporary directory
+Request a unique temporary directory for functional tests
 --------------------------------------------------------------
 
-For functional tests one often needs to create some files
-and pass them to application objects.  pytest provides
-:ref:`builtinfixtures` which allow to request arbitrary
-resources, for example a unique temporary directory::
+``pytest`` provides `Builtin fixtures/function arguments <https://docs.pytest.org/en/latest/builtin.html#builtinfixtures>`_ to request arbitrary resources, like a unique temporary directory::
 
     # content of test_tmpdir.py
     def test_needsfiles(tmpdir):
         print (tmpdir)
         assert 0
 
-We list the name ``tmpdir`` in the test function signature and
-``pytest`` will lookup and call a fixture factory to create the resource
-before performing the test function call.  Let's just run it::
+List the name ``tmpdir`` in the test function signature and ``pytest`` will lookup and call a fixture factory to create the resource before performing the test function call. Before the test runs, ``pytest`` creates a unique-per-test-invocation temporary directory::
 
     $ pytest -q test_tmpdir.py
     F                                                                    [100%]
     ================================= FAILURES =================================
     _____________________________ test_needsfiles ______________________________
-    
+
     tmpdir = local('PYTEST_TMPDIR/test_needsfiles0')
-    
+
         def test_needsfiles(tmpdir):
             print (tmpdir)
     >       assert 0
     E       assert 0
-    
+
     test_tmpdir.py:3: AssertionError
     --------------------------- Captured stdout call ---------------------------
     PYTEST_TMPDIR/test_needsfiles0
     1 failed in 0.12 seconds
 
-Before the test runs, a unique-per-test-invocation temporary directory
-was created.  More info at :ref:`tmpdir handling`.
+More info on tmpdir handling is available at :ref:`Temporary directories and files <tmpdir handling>`.
 
-You can find out what kind of builtin :ref:`fixtures` exist by typing::
+Find out what kind of builtin :ref:`pytest fixtures <fixtures>` exist with the command::
 
     pytest --fixtures   # shows builtin and custom fixtures
 
-Where to go next
+Note that this command omits fixtures with leading ``_`` unless the ``-v`` option is added.
+
+Continue reading
 -------------------------------------
 
-Here are a few suggestions where to go next:
+Check out additional pytest resources to help you customize tests for your unique workflow:
 
-* :ref:`cmdline` for command line invocation examples
-* :ref:`good practices <goodpractices>` for virtualenv, test layout
-* :ref:`existingtestsuite` for working with pre-existing tests
-* :ref:`fixtures` for providing a functional baseline to your tests
-* :ref:`plugins` managing and writing plugins
+* ":ref:`cmdline`" for command line invocation examples
+* ":ref:`existingtestsuite`" for working with pre-existing tests
+* ":ref:`mark`" for information on the ``pytest.mark`` mechanism
+* ":ref:`fixtures`" for providing a functional baseline to your tests
+* ":ref:`plugins`" for managing and writing plugins
+* ":ref:`goodpractices`" for virtualenv and test layouts
 
 .. include:: links.inc
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/goodpractices.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/goodpractices.rst
@@ -140,17 +140,17 @@ Note that this layout also works in conj
     files from your directories it should just work on Python3.3 and above.  From
     "inlined tests", however, you will need to use absolute imports for
     getting at your application code.
 
 .. _`test package name`:
 
 .. note::
 
-    If ``pytest`` finds a "a/b/test_module.py" test file while
+    If ``pytest`` finds an "a/b/test_module.py" test file while
     recursing into the filesystem it determines the import name
     as follows:
 
     * determine ``basedir``: this is the first "upward" (towards the root)
       directory not containing an ``__init__.py``.  If e.g. both ``a``
       and ``b`` contain an ``__init__.py`` file then the parent directory
       of ``a`` will become the ``basedir``.
 
@@ -163,23 +163,23 @@ Note that this layout also works in conj
       names map directly to the import names.
 
     The reason for this somewhat evolved importing technique is
     that in larger projects multiple test modules might import
     from each other and thus deriving a canonical import name helps
     to avoid surprises such as a test module getting imported twice.
 
 
-.. _`virtualenv`: http://pypi.python.org/pypi/virtualenv
+.. _`virtualenv`: https://pypi.org/project/virtualenv/
 .. _`buildout`: http://www.buildout.org/
-.. _pip: http://pypi.python.org/pypi/pip
+.. _pip: https://pypi.org/project/pip/
 
 .. _`use tox`:
 
-Tox
+tox
 ------
 
 For development, we recommend to use virtualenv_ environments and pip_
 for installing your application and any dependencies
 as well as the ``pytest`` package itself. This ensures your code and
 dependencies are isolated from the system Python installation.
 
 You can then install your package in "editable" mode::
@@ -189,40 +189,40 @@ You can then install your package in "ed
 which lets you change your source code (both tests and application) and rerun tests at will.
 This is similar to running `python setup.py develop` or `conda develop` in that it installs
 your package using a symlink to your development code.
 
 Once you are done with your work and want to make sure that your actual
 package passes all tests you may want to look into `tox`_, the
 virtualenv test automation tool and its `pytest support
 <https://tox.readthedocs.io/en/latest/example/pytest.html>`_.
-Tox helps you to setup virtualenv environments with pre-defined
+tox helps you to setup virtualenv environments with pre-defined
 dependencies and then executing a pre-configured test command with
 options.  It will run tests against the installed package and not
 against your source code checkout, helping to detect packaging
 glitches.
 
 
 Integrating with setuptools / ``python setup.py test`` / ``pytest-runner``
 --------------------------------------------------------------------------
 
 You can integrate test runs into your setuptools based project
-with the `pytest-runner <https://pypi.python.org/pypi/pytest-runner>`_ plugin.
+with the `pytest-runner <https://pypi.org/project/pytest-runner/>`_ plugin.
 
 Add this to ``setup.py`` file:
 
 .. code-block:: python
 
     from setuptools import setup
 
     setup(
-        #...,
-        setup_requires=['pytest-runner', ...],
-        tests_require=['pytest', ...],
-        #...,
+        # ...,
+        setup_requires=["pytest-runner", ...],
+        tests_require=["pytest", ...],
+        # ...,
     )
 
 
 And create an alias into ``setup.cfg`` file:
 
 
 .. code-block:: ini
 
@@ -258,35 +258,37 @@ your own setuptools Test command for inv
 .. code-block:: python
 
     import sys
 
     from setuptools.command.test import test as TestCommand
 
 
     class PyTest(TestCommand):
-        user_options = [('pytest-args=', 'a', "Arguments to pass to pytest")]
+        user_options = [("pytest-args=", "a", "Arguments to pass to pytest")]
 
         def initialize_options(self):
             TestCommand.initialize_options(self)
-            self.pytest_args = ''
+            self.pytest_args = ""
 
         def run_tests(self):
             import shlex
-            #import here, cause outside the eggs aren't loaded
+
+            # import here, cause outside the eggs aren't loaded
             import pytest
+
             errno = pytest.main(shlex.split(self.pytest_args))
             sys.exit(errno)
 
 
     setup(
-        #...,
-        tests_require=['pytest'],
-        cmdclass = {'test': PyTest},
-        )
+        # ...,
+        tests_require=["pytest"],
+        cmdclass={"test": PyTest},
+    )
 
 Now if you run::
 
     python setup.py test
 
 this will download ``pytest`` if needed and then run your tests
 as you would expect it to. You can pass a single string of arguments
 using the ``--pytest-args`` or ``-a`` command-line option. For example::
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/index.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/index.rst
@@ -12,39 +12,40 @@ scales to support complex functional tes
 An example of a simple test:
 
 .. code-block:: python
 
     # content of test_sample.py
     def inc(x):
         return x + 1
 
+
     def test_answer():
         assert inc(3) == 5
 
 
 To execute it::
 
     $ pytest
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 1 item
-    
+
     test_sample.py F                                                     [100%]
-    
+
     ================================= FAILURES =================================
     _______________________________ test_answer ________________________________
-    
+
         def test_answer():
     >       assert inc(3) == 5
     E       assert 4 == 5
     E        +  where 4 = inc(3)
-    
-    test_sample.py:5: AssertionError
+
+    test_sample.py:6: AssertionError
     ========================= 1 failed in 0.12 seconds =========================
 
 Due to ``pytest``'s detailed assertion introspection, only plain ``assert`` statements are used.
 See :ref:`Getting Started <getstarted>` for more examples.
 
 
 Features
 --------
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/links.inc
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/links.inc
@@ -2,20 +2,20 @@
 .. _`skipping plugin`: plugin/skipping.html
 .. _`funcargs mechanism`: funcargs.html
 .. _`doctest.py`: http://docs.python.org/library/doctest.html
 .. _`xUnit style setup`: xunit_setup.html
 .. _`pytest_nose`: plugin/nose.html
 .. _`reStructured Text`: http://docutils.sourceforge.net
 .. _`Python debugger`: http://docs.python.org/lib/module-pdb.html
 .. _nose: https://nose.readthedocs.io/en/latest/
-.. _pytest: http://pypi.python.org/pypi/pytest
+.. _pytest: https://pypi.org/project/pytest/
 .. _mercurial: http://mercurial.selenic.com/wiki/
-.. _`setuptools`: http://pypi.python.org/pypi/setuptools
+.. _`setuptools`: https://pypi.org/project/setuptools/
 .. _`easy_install`:
 .. _`distribute docs`:
-.. _`distribute`: http://pypi.python.org/pypi/distribute
-.. _`pip`: http://pypi.python.org/pypi/pip
-.. _`virtualenv`: http://pypi.python.org/pypi/virtualenv
+.. _`distribute`: https://pypi.org/project/distribute/
+.. _`pip`: https://pypi.org/project/pip/
+.. _`virtualenv`: https://pypi.org/project/virtualenv/
 .. _hudson: http://hudson-ci.org/
 .. _jenkins: http://jenkins-ci.org/
 .. _tox: http://testrun.org/tox
 .. _pylib: https://py.readthedocs.io/en/latest/
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/logging.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/logging.rst
@@ -1,126 +1,102 @@
 .. _logging:
 
 Logging
 -------
 
-.. versionadded 3.3.0
-
-.. note::
+.. versionadded:: 3.3
+.. versionchanged:: 3.4
 
-   This feature is a drop-in replacement for the `pytest-catchlog
-   <https://pypi.org/project/pytest-catchlog/>`_ plugin and they will conflict
-   with each other. The backward compatibility API with ``pytest-capturelog``
-   has been dropped when this feature was introduced, so if for that reason you
-   still need ``pytest-catchlog`` you can disable the internal feature by
-   adding to your ``pytest.ini``:
-
-   .. code-block:: ini
-
-       [pytest]
-           addopts=-p no:logging
-
-Log messages are captured by default and for each failed test will be shown in
-the same manner as captured stdout and stderr.
+pytest captures log messages of level ``WARNING`` or above automatically and displays them in their own section
+for each failed test in the same manner as captured stdout and stderr.
 
 Running without options::
 
     pytest
 
 Shows failed tests like so::
 
     ----------------------- Captured stdlog call ----------------------
-    test_reporting.py    26 INFO     text going to logger
+    test_reporting.py    26 WARNING  text going to logger
     ----------------------- Captured stdout call ----------------------
     text going to stdout
     ----------------------- Captured stderr call ----------------------
     text going to stderr
     ==================== 2 failed in 0.02 seconds =====================
 
 By default each captured log message shows the module, line number, log level
-and message.  Showing the exact module and line number is useful for testing and
-debugging.  If desired the log format and date format can be specified to
-anything that the logging module supports.
+and message.
 
-Running pytest specifying formatting options::
+If desired the log and date format can be specified to
+anything that the logging module supports by passing specific formatting options::
 
     pytest --log-format="%(asctime)s %(levelname)s %(message)s" \
             --log-date-format="%Y-%m-%d %H:%M:%S"
 
 Shows failed tests like so::
 
     ----------------------- Captured stdlog call ----------------------
-    2010-04-10 14:48:44 INFO text going to logger
+    2010-04-10 14:48:44 WARNING text going to logger
     ----------------------- Captured stdout call ----------------------
     text going to stdout
     ----------------------- Captured stderr call ----------------------
     text going to stderr
     ==================== 2 failed in 0.02 seconds =====================
 
-These options can also be customized through a configuration file:
+These options can also be customized through ``pytest.ini`` file:
 
 .. code-block:: ini
 
     [pytest]
     log_format = %(asctime)s %(levelname)s %(message)s
     log_date_format = %Y-%m-%d %H:%M:%S
 
-Further it is possible to disable reporting logs on failed tests completely
-with::
-
-    pytest --no-print-logs
+Further it is possible to disable reporting of captured content (stdout,
+stderr and logs) on failed tests completely with::
 
-Or in you ``pytest.ini``:
-
-.. code-block:: ini
-
-  [pytest]
-  log_print = False
+    pytest --show-capture=no
 
 
-Shows failed tests in the normal manner as no logs were captured::
-
-    ----------------------- Captured stdout call ----------------------
-    text going to stdout
-    ----------------------- Captured stderr call ----------------------
-    text going to stderr
-    ==================== 2 failed in 0.02 seconds =====================
+caplog fixture
+^^^^^^^^^^^^^^
 
 Inside tests it is possible to change the log level for the captured log
 messages.  This is supported by the ``caplog`` fixture::
 
     def test_foo(caplog):
         caplog.set_level(logging.INFO)
         pass
 
-By default the level is set on the handler used to catch the log messages,
+By default the level is set on the root logger,
 however as a convenience it is also possible to set the log level of any
 logger::
 
     def test_foo(caplog):
         caplog.set_level(logging.CRITICAL, logger='root.baz')
         pass
 
+The log levels set are restored automatically at the end of the test.
+
 It is also possible to use a context manager to temporarily change the log
-level::
+level inside a ``with`` block::
 
     def test_bar(caplog):
         with caplog.at_level(logging.INFO):
             pass
 
-Again, by default the level of the handler is affected but the level of any
+Again, by default the level of the root logger is affected but the level of any
 logger can be changed instead with::
 
     def test_bar(caplog):
         with caplog.at_level(logging.CRITICAL, logger='root.baz'):
             pass
 
 Lastly all the logs sent to the logger during the test run are made available on
-the fixture in the form of both the LogRecord instances and the final log text.
+the fixture in the form of both the ``logging.LogRecord`` instances and the final log text.
 This is useful for when you want to assert on the contents of a message::
 
     def test_baz(caplog):
         func_under_test()
         for record in caplog.records:
             assert record.levelname != 'CRITICAL'
         assert 'wally' not in caplog.text
 
@@ -141,22 +117,53 @@ severity and message::
 You can call ``caplog.clear()`` to reset the captured log records in a test::
 
     def test_something_with_clearing_records(caplog):
         some_method_that_creates_log_records()
         caplog.clear()
         your_test_method()
         assert ['Foo'] == [rec.message for rec in caplog.records]
 
+
+The ``caplog.records`` attribute contains records from the current stage only, so
+inside the ``setup`` phase it contains only setup logs, same with the ``call`` and
+``teardown`` phases.
+
+To access logs from other stages, use the ``caplog.get_records(when)`` method. As an example,
+if you want to make sure that tests which use a certain fixture never log any warnings, you can inspect
+the records for the ``setup`` and ``call`` stages during teardown like so:
+
+.. code-block:: python
+
+
+    @pytest.fixture
+    def window(caplog):
+        window = create_window()
+        yield window
+        for when in ("setup", "call"):
+            messages = [
+                x.message for x in caplog.get_records(when) if x.level == logging.WARNING
+            ]
+            if messages:
+                pytest.fail(
+                    "warning messages encountered during testing: {}".format(messages)
+                )
+
+
+
+The full API is available at :class:`_pytest.logging.LogCaptureFixture`.
+
+
+.. _live_logs:
+
 Live Logs
 ^^^^^^^^^
 
-By default, pytest will output any logging records with a level higher or
-equal to WARNING. In order to actually see these logs in the console you have to
-disable pytest output capture by passing ``-s``.
+By setting the :confval:`log_cli` configuration option to ``true``, pytest will output
+logging records as they are emitted directly into the console.
 
 You can specify the logging level for which log records with equal or higher
 level are printed to the console by passing ``--log-cli-level``. This setting
 accepts the logging level names as seen in python's documentation or an integer
 as the logging level num.
 
 Additionally, you can also specify ``--log-cli-format`` and
 ``--log-cli-date-format`` which mirror and default to ``--log-format`` and
@@ -185,8 +192,54 @@ Additionally, you can also specify ``--l
 
 All of the log file options can also be set in the configuration INI file. The
 option names are:
 
 * ``log_file``
 * ``log_file_level``
 * ``log_file_format``
 * ``log_file_date_format``
+
+.. _log_release_notes:
+
+Release notes
+^^^^^^^^^^^^^
+
+This feature was introduced as a drop-in replacement for the `pytest-catchlog
+<https://pypi.org/project/pytest-catchlog/>`_ plugin and they conflict
+with each other. The backward compatibility API with ``pytest-capturelog``
+has been dropped when this feature was introduced, so if for that reason you
+still need ``pytest-catchlog`` you can disable the internal feature by
+adding to your ``pytest.ini``:
+
+.. code-block:: ini
+
+   [pytest]
+       addopts=-p no:logging
+
+
+.. _log_changes_3_4:
+
+Incompatible changes in pytest 3.4
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+This feature was introduced in ``3.3`` and some **incompatible changes** have been
+made in ``3.4`` after community feedback:
+
+* Log levels are no longer changed unless explicitly requested by the :confval:`log_level` configuration
+  or ``--log-level`` command-line options. This allows users to configure logger objects themselves.
+* :ref:`Live Logs <live_logs>` is now disabled by default and can be enabled setting the
+  :confval:`log_cli` configuration option to ``true``. When enabled, the verbosity is increased so logging for each
+  test is visible.
+* :ref:`Live Logs <live_logs>` are now sent to ``sys.stdout`` and no longer require the ``-s`` command-line option
+  to work.
+
+If you want to partially restore the logging behavior of version ``3.3``, you can add this options to your ``ini``
+file:
+
+.. code-block:: ini
+
+    [pytest]
+    log_cli=true
+    log_level=NOTSET
+
+More details about the discussion that lead to this changes can be read in
+issue `#3013 <https://github.com/pytest-dev/pytest/issues/3013>`_.
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/mark.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/mark.rst
@@ -1,15 +1,14 @@
 
 .. _mark:
 
 Marking test functions with attributes
 =================================================================
 
-.. currentmodule:: _pytest.mark
 
 By using the ``pytest.mark`` helper you can easily set
 metadata on your test functions. There are
 some builtin markers, for example:
 
 * :ref:`skip <skip>` - always skip a test function
 * :ref:`skipif <skipif>` - skip a test function if a certain condition is met
 * :ref:`xfail <xfail>` - produce an "expected failure" outcome if a certain
@@ -22,20 +21,139 @@ to whole test classes or modules. See :r
 which also serve as documentation.
 
 .. note::
 
     Marks can only be applied to tests, having no effect on
     :ref:`fixtures <fixtures>`.
 
 
-API reference for mark related objects
-------------------------------------------------
+Raising errors on unknown marks: --strict
+-----------------------------------------
+
+When the ``--strict`` command-line flag is passed, any marks not registered in the ``pytest.ini`` file will trigger an error.
+
+Marks can be registered like this:
+
+.. code-block:: ini
+
+    [pytest]
+    markers =
+        slow
+        serial
+
+This can be used to prevent users mistyping mark names by accident. Test suites that want to enforce this
+should add ``--strict`` to ``addopts``:
+
+.. code-block:: ini
+
+    [pytest]
+    addopts = --strict
+    markers =
+        slow
+        serial
+
+
+.. `marker-iteration`
+
+Marker revamp and iteration
+---------------------------
 
-.. autoclass:: MarkGenerator
-    :members:
+.. versionadded:: 3.6
+
+pytest's marker implementation traditionally worked by simply updating the ``__dict__`` attribute of functions to add markers, in a cumulative manner. As a result of the this, markers would unintendely be passed along class hierarchies in surprising ways plus the API for retriving them was inconsistent, as markers from parameterization would be stored differently than markers applied using the ``@pytest.mark`` decorator and markers added via ``node.add_marker``.
+
+This state of things made it technically next to impossible to use data from markers correctly without having a deep understanding of the internals, leading to subtle and hard to understand bugs in more advanced usages.
+
+Depending on how a marker got declared/changed one would get either a ``MarkerInfo`` which might contain markers from sibling classes,
+``MarkDecorators`` when marks came from parameterization or from a ``node.add_marker`` call, discarding prior marks. Also ``MarkerInfo`` acts like a single mark, when it in fact represents a merged view on multiple marks with the same name.
+
+On top of that markers where not accessible the same way for modules, classes, and functions/methods,
+in fact, markers where only accessible in functions, even if they where declared on classes/modules.
+
+A new API to access markers has been introduced in pytest 3.6 in order to solve the problems with the initial design, providing :func:`_pytest.nodes.Node.iter_markers` method to iterate over markers in a consistent manner and reworking the internals, which solved great deal of problems with the initial design.
+
+
+.. _update marker code:
+
+Updating code
+~~~~~~~~~~~~~
+
+The old ``Node.get_marker(name)`` function is considered deprecated because it returns an internal ``MarkerInfo`` object
+which contains the merged name, ``*args`` and ``**kwargs`` of all the markers which apply to that node.
+
+In general there are two scenarios on how markers should be handled:
+
+1. Marks overwrite each other. Order matters but you only want to think of your mark as a single item. E.g.
+``log_level('info')`` at a module level can be overwritten by ``log_level('debug')`` for a specific test.
+
+    In this case replace use ``Node.get_closest_marker(name)``:
+
+    .. code-block:: python
 
-.. autoclass:: MarkDecorator
-    :members:
+        # replace this:
+        marker = item.get_marker("log_level")
+        if marker:
+            level = marker.args[0]
+
+        # by this:
+        marker = item.get_closest_marker("log_level")
+        if marker:
+            level = marker.args[0]
+
+2. Marks compose additive. E.g. ``skipif(condition)`` marks means you just want to evaluate all of them,
+order doesn't even matter. You probably want to think of your marks as a set here.
+
+   In this case iterate over each mark and handle their ``*args`` and ``**kwargs`` individually.
+
+   .. code-block:: python
+
+        # replace this
+        skipif = item.get_marker("skipif")
+        if skipif:
+            for condition in skipif.args:
+                # eval condition
+                ...
+
+        # by this:
+        for skipif in item.iter_markers("skipif"):
+            condition = skipif.args[0]
+            # eval condition
+
+
+If you are unsure or have any questions, please consider opening
+`an issue <https://github.com/pytest-dev/pytest/issues>`_.
 
-.. autoclass:: MarkInfo
-    :members:
+Related issues
+~~~~~~~~~~~~~~
+
+Here is a non-exhaustive list of issues fixed by the new implementation:
+
+* Marks don't pick up nested classes (`#199 <https://github.com/pytest-dev/pytest/issues/199>`_).
+
+* markers stains on all related classes (`#568 <https://github.com/pytest-dev/pytest/issues/568>`_).
+
+* combining marks - args and kwargs calculation (`#2897 <https://github.com/pytest-dev/pytest/issues/2897>`_).
+
+* ``request.node.get_marker('name')`` returns ``None`` for markers applied in classes (`#902 <https://github.com/pytest-dev/pytest/issues/902>`_).
+
+* marks applied in parametrize are stored as markdecorator (`#2400 <https://github.com/pytest-dev/pytest/issues/2400>`_).
+
+* fix marker interaction in a backward incompatible way (`#1670 <https://github.com/pytest-dev/pytest/issues/1670>`_).
 
+* Refactor marks to get rid of the current "marks transfer" mechanism (`#2363 <https://github.com/pytest-dev/pytest/issues/2363>`_).
+
+* Introduce FunctionDefinition node, use it in generate_tests (`#2522 <https://github.com/pytest-dev/pytest/issues/2522>`_).
+
+* remove named marker attributes and collect markers in items (`#891 <https://github.com/pytest-dev/pytest/issues/891>`_).
+
+* skipif mark from parametrize hides module level skipif mark (`#1540 <https://github.com/pytest-dev/pytest/issues/1540>`_).
+
+* skipif + parametrize not skipping tests (`#1296 <https://github.com/pytest-dev/pytest/issues/1296>`_).
+
+* marker transfer incompatible with inheritance (`#535 <https://github.com/pytest-dev/pytest/issues/535>`_).
+
+More details can be found in the `original PR <https://github.com/pytest-dev/pytest/pull/3317>`_.
+
+.. note::
+
+    in a future major relase of pytest we will introduce class based markers,
+    at which points markers will no longer be limited to instances of :py:class:`Mark`
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/monkeypatch.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/monkeypatch.rst
@@ -30,46 +30,60 @@ patch this function before calling into 
     def test_mytest(monkeypatch):
         def mockreturn(path):
             return '/abc'
         monkeypatch.setattr(os.path, 'expanduser', mockreturn)
         x = getssh()
         assert x == '/abc/.ssh'
 
 Here our test function monkeypatches ``os.path.expanduser`` and
-then calls into a function that calls it.  After the test function 
+then calls into a function that calls it.  After the test function
 finishes the ``os.path.expanduser`` modification will be undone.
 
 example: preventing "requests" from remote operations
 ------------------------------------------------------
 
 If you want to prevent the "requests" library from performing http
 requests in all your tests, you can do::
 
     # content of conftest.py
     import pytest
     @pytest.fixture(autouse=True)
     def no_requests(monkeypatch):
         monkeypatch.delattr("requests.sessions.Session.request")
 
 This autouse fixture will be executed for each test function and it
-will delete the method ``request.session.Session.request`` 
+will delete the method ``request.session.Session.request``
 so that any attempts within tests to create http requests will fail.
 
 
 .. note::
-    
+
     Be advised that it is not recommended to patch builtin functions such as ``open``,
     ``compile``, etc., because it might break pytest's internals. If that's
-    unavoidable, passing ``--tb=native``, ``--assert=plain`` and ``--capture=no`` might 
+    unavoidable, passing ``--tb=native``, ``--assert=plain`` and ``--capture=no`` might
     help although there's no guarantee.
-    
+
+.. note::
 
-Method reference of the monkeypatch fixture
--------------------------------------------
+    Mind that patching ``stdlib`` functions and some third-party libraries used by pytest
+    might break pytest itself, therefore in those cases it is recommended to use
+    :meth:`MonkeyPatch.context` to limit the patching to the block you want tested:
+
+    .. code-block:: python
+
+        import functools
+
 
-.. autoclass:: MonkeyPatch
-    :members:
+        def test_partial(monkeypatch):
+            with monkeypatch.context() as m:
+                m.setattr(functools, "partial", 3)
+                assert functools.partial == 3
+
+    See issue `#3290 <https://github.com/pytest-dev/pytest/issues/3290>`_ for details.
 
-``monkeypatch.setattr/delattr/delitem/delenv()`` all
-by default raise an Exception if the target does not exist.
-Pass ``raising=False`` if you want to skip this check.
+
+.. currentmodule:: _pytest.monkeypatch
 
+API Reference
+-------------
+
+Consult the docs for the :class:`MonkeyPatch` class.
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/nose.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/nose.rst
@@ -53,23 +53,20 @@ Unsupported idioms / known issues
   If you place a conftest.py file in the root directory of your project
   (as determined by pytest) pytest will run tests "nose style" against
   the code below that directory by adding it to your ``sys.path`` instead of
   running against your installed code.
 
   You may find yourself wanting to do this if you ran ``python setup.py install``
   to set up your project, as opposed to ``python setup.py develop`` or any of
   the package manager equivalents.  Installing with develop in a
-  virtual environment like Tox is recommended over this pattern.
+  virtual environment like tox is recommended over this pattern.
 
 - nose-style doctests are not collected and executed correctly,
   also doctest fixtures don't work.
 
 - no nose-configuration is recognized.
 
 - ``yield``-based methods don't support ``setup`` properly because
   the ``setup`` method is always called in the same class instance.
   There are no plans to fix this currently because ``yield``-tests
   are deprecated in pytest 3.0, with ``pytest.mark.parametrize``
   being the recommended alternative.
-
-
-
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/parametrize.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/parametrize.rst
@@ -6,39 +6,39 @@
 
 .. _`parametrize-basics`:
 
 Parametrizing fixtures and test functions
 ==========================================================================
 
 pytest enables test parametrization at several levels:
 
-- :py:func:`pytest.fixture` allows one to :ref:`parametrize fixture 
+- :py:func:`pytest.fixture` allows one to :ref:`parametrize fixture
   functions <fixture-parametrize>`.
 
-* `@pytest.mark.parametrize`_ allows one to define multiple sets of 
+* `@pytest.mark.parametrize`_ allows one to define multiple sets of
   arguments and fixtures at the test function or class.
 
-* `pytest_generate_tests`_ allows one to define custom parametrization 
+* `pytest_generate_tests`_ allows one to define custom parametrization
   schemes or extensions.
 
 .. _parametrizemark:
 .. _`@pytest.mark.parametrize`:
 
 
 ``@pytest.mark.parametrize``: parametrizing test functions
 ---------------------------------------------------------------------
 
 .. regendoc: wipe
 
 .. versionadded:: 2.2
 .. versionchanged:: 2.4
     Several improvements.
 
-The builtin ``pytest.mark.parametrize`` decorator enables
+The builtin :ref:`pytest.mark.parametrize ref` decorator enables
 parametrization of arguments for a test function.  Here is a typical example
 of a test function that implements checking that a certain input leads
 to an expected output::
 
     # content of test_expectation.py
     import pytest
     @pytest.mark.parametrize("test_input,expected", [
         ("3+5", 8),
@@ -52,34 +52,34 @@ Here, the ``@parametrize`` decorator def
 tuples so that the ``test_eval`` function will run three times using
 them in turn::
 
     $ pytest
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 3 items
-    
+
     test_expectation.py ..F                                              [100%]
-    
+
     ================================= FAILURES =================================
     ____________________________ test_eval[6*9-42] _____________________________
-    
+
     test_input = '6*9', expected = 42
-    
+
         @pytest.mark.parametrize("test_input,expected", [
             ("3+5", 8),
             ("2+4", 6),
             ("6*9", 42),
         ])
         def test_eval(test_input, expected):
     >       assert eval(test_input) == expected
     E       AssertionError: assert 54 == 42
     E        +  where 54 = eval('6*9')
-    
+
     test_expectation.py:8: AssertionError
     ==================== 1 failed, 2 passed in 0.12 seconds ====================
 
 As designed in this example, only one pair of input/output values fails
 the simple test function.  And as usual with test function arguments,
 you can see the ``input`` and ``output`` values in the traceback.
 
 Note that you could also use the parametrize marker on a class or a module
@@ -101,35 +101,35 @@ for example with the builtin ``mark.xfai
 
 Let's run this::
 
     $ pytest
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 3 items
-    
+
     test_expectation.py ..x                                              [100%]
-    
+
     =================== 2 passed, 1 xfailed in 0.12 seconds ====================
 
 The one parameter set which caused a failure previously now
 shows up as an "xfailed (expected to fail)" test.
 
 To get all combinations of multiple parametrized arguments you can stack
 ``parametrize`` decorators::
 
     import pytest
     @pytest.mark.parametrize("x", [0, 1])
     @pytest.mark.parametrize("y", [2, 3])
     def test_foo(x, y):
         pass
 
-This will run the test with the arguments set to ``x=0/y=2``, ``x=0/y=3``, ``x=1/y=2`` and
-``x=1/y=3``.
+This will run the test with the arguments set to ``x=0/y=2``, ``x=1/y=2``,
+``x=0/y=3``, and ``x=1/y=3`` exhausting parameters in the order of the decorators.
 
 .. _`pytest_generate_tests`:
 
 Basic ``pytest_generate_tests`` example
 ---------------------------------------------
 
 Sometimes you may want to implement your own parametrization scheme
 or implement some dynamism for determining the parameters or scope
@@ -169,49 +169,40 @@ If we now pass two stringinput values, o
     2 passed in 0.12 seconds
 
 Let's also run with a stringinput that will lead to a failing test::
 
     $ pytest -q --stringinput="!" test_strings.py
     F                                                                    [100%]
     ================================= FAILURES =================================
     ___________________________ test_valid_string[!] ___________________________
-    
+
     stringinput = '!'
-    
+
         def test_valid_string(stringinput):
     >       assert stringinput.isalpha()
     E       AssertionError: assert False
     E        +  where False = <built-in method isalpha of str object at 0xdeadbeef>()
     E        +    where <built-in method isalpha of str object at 0xdeadbeef> = '!'.isalpha
-    
+
     test_strings.py:3: AssertionError
     1 failed in 0.12 seconds
 
 As expected our test function fails.
 
 If you don't specify a stringinput it will be skipped because
 ``metafunc.parametrize()`` will be called with an empty parameter
 list::
 
     $ pytest -q -rs test_strings.py
     s                                                                    [100%]
     ========================= short test summary info ==========================
     SKIP [1] test_strings.py: got empty parameter set ['stringinput'], function test_valid_string at $REGENDOC_TMPDIR/test_strings.py:1
     1 skipped in 0.12 seconds
 
-Note that when calling ``metafunc.parametrize`` multiple times with different parameter sets, all parameter names across 
+Note that when calling ``metafunc.parametrize`` multiple times with different parameter sets, all parameter names across
 those sets cannot be duplicated, otherwise an error will be raised.
 
 More examples
 -------------
 
 For further examples, you might want to look at :ref:`more
 parametrization examples <paramexamples>`.
-
-.. _`metafunc object`:
-
-The **metafunc** object
--------------------------------------------
-
-.. currentmodule:: _pytest.python
-.. autoclass:: Metafunc
-    :members:
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/plugins.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/plugins.rst
@@ -15,75 +15,82 @@ Installing a third party plugin can be e
 
 If a plugin is installed, ``pytest`` automatically finds and integrates it,
 there is no need to activate it.
 
 Here is a little annotated list for some popular plugins:
 
 .. _`django`: https://www.djangoproject.com/
 
-* `pytest-django <http://pypi.python.org/pypi/pytest-django>`_: write tests
+* `pytest-django <https://pypi.org/project/pytest-django/>`_: write tests
   for `django`_ apps, using pytest integration.
 
-* `pytest-twisted <http://pypi.python.org/pypi/pytest-twisted>`_: write tests
+* `pytest-twisted <https://pypi.org/project/pytest-twisted/>`_: write tests
   for `twisted <http://twistedmatrix.com>`_ apps, starting a reactor and
   processing deferreds from test functions.
 
-* `pytest-cov <http://pypi.python.org/pypi/pytest-cov>`_:
+* `pytest-cov <https://pypi.org/project/pytest-cov/>`_:
   coverage reporting, compatible with distributed testing
 
-* `pytest-xdist <http://pypi.python.org/pypi/pytest-xdist>`_:
+* `pytest-xdist <https://pypi.org/project/pytest-xdist/>`_:
   to distribute tests to CPUs and remote hosts, to run in boxed
   mode which allows to survive segmentation faults, to run in
   looponfailing mode, automatically re-running failing tests
   on file changes.
 
-* `pytest-instafail <http://pypi.python.org/pypi/pytest-instafail>`_:
+* `pytest-instafail <https://pypi.org/project/pytest-instafail/>`_:
   to report failures while the test run is happening.
 
-* `pytest-bdd <http://pypi.python.org/pypi/pytest-bdd>`_ and
-  `pytest-konira <http://pypi.python.org/pypi/pytest-konira>`_
+* `pytest-bdd <https://pypi.org/project/pytest-bdd/>`_ and
+  `pytest-konira <https://pypi.org/project/pytest-konira/>`_
   to write tests using behaviour-driven testing.
 
-* `pytest-timeout <http://pypi.python.org/pypi/pytest-timeout>`_:
+* `pytest-timeout <https://pypi.org/project/pytest-timeout/>`_:
   to timeout tests based on function marks or global definitions.
 
-* `pytest-pep8 <http://pypi.python.org/pypi/pytest-pep8>`_:
+* `pytest-pep8 <https://pypi.org/project/pytest-pep8/>`_:
   a ``--pep8`` option to enable PEP8 compliance checking.
 
-* `pytest-flakes <https://pypi.python.org/pypi/pytest-flakes>`_:
+* `pytest-flakes <https://pypi.org/project/pytest-flakes/>`_:
   check source code with pyflakes.
 
-* `oejskit <http://pypi.python.org/pypi/oejskit>`_:
+* `oejskit <https://pypi.org/project/oejskit/>`_:
   a plugin to run javascript unittests in live browsers.
 
 To see a complete list of all plugins with their latest testing
 status against different pytest and Python versions, please visit
 `plugincompat <http://plugincompat.herokuapp.com/>`_.
 
 You may also discover more plugins through a `pytest- pypi.python.org search`_.
 
+.. _`pytest- pypi.python.org search`: https://pypi.org/search/?q=pytest-
+
+
 .. _`available installable plugins`:
-.. _`pytest- pypi.python.org search`: http://pypi.python.org/pypi?%3Aaction=search&term=pytest-&submit=search
-
 
 Requiring/Loading plugins in a test module or conftest file
 -----------------------------------------------------------
 
 You can require plugins in a test module or a conftest file like this::
 
     pytest_plugins = "myapp.testsupport.myplugin",
 
 When the test module or conftest plugin is loaded the specified plugins
 will be loaded as well.
 
     pytest_plugins = "myapp.testsupport.myplugin"
 
 which will import the specified module as a ``pytest`` plugin.
 
+.. note::
+    Requiring plugins using a ``pytest_plugins`` variable in non-root
+    ``conftest.py`` files is deprecated. See
+    :ref:`full explanation <requiring plugins in non-root conftests>`
+    in the Writing plugins section.
+
 .. _`findpluginname`:
 
 Finding out which plugins are active
 ------------------------------------
 
 If you want to find out which plugins are active in your
 environment you can type::
 
@@ -115,40 +122,8 @@ this option to your ``pytest.ini`` file:
 
 Alternatively to disable it only in certain environments (for example in a
 CI server), you can set ``PYTEST_ADDOPTS`` environment variable to
 ``-p no:name``.
 
 See :ref:`findpluginname` for how to obtain the name of a plugin.
 
 .. _`builtin plugins`:
-
-Pytest default plugin reference
--------------------------------
-
-
-You can find the source code for the following plugins
-in the `pytest repository <https://github.com/pytest-dev/pytest>`_.
-
-.. autosummary::
-
-    _pytest.assertion
-    _pytest.cacheprovider
-    _pytest.capture
-    _pytest.config
-    _pytest.doctest
-    _pytest.helpconfig
-    _pytest.junitxml
-    _pytest.mark
-    _pytest.monkeypatch
-    _pytest.nose
-    _pytest.pastebin
-    _pytest.debugging
-    _pytest.pytester
-    _pytest.python
-    _pytest.recwarn
-    _pytest.resultlog
-    _pytest.runner
-    _pytest.main
-    _pytest.skipping
-    _pytest.terminal
-    _pytest.tmpdir
-    _pytest.unittest
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/projects.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/projects.rst
@@ -27,50 +27,50 @@ Here are some examples of projects using
 * the `MoinMoin <http://moinmo.in>`_ Wiki Engine
 * `sentry <https://getsentry.com/welcome/>`_, realtime app-maintenance and exception tracking
 * `Astropy <http://www.astropy.org/>`_ and `affiliated packages <http://www.astropy.org/affiliated/index.html>`_
 * `tox <http://testrun.org/tox>`_, virtualenv/Hudson integration tool
 * `PIDA <http://pida.co.uk>`_ framework for integrated development
 * `PyPM <http://code.activestate.com/pypm/>`_ ActiveState's package manager
 * `Fom <http://packages.python.org/Fom/>`_ a fluid object mapper for FluidDB
 * `applib <https://github.com/ActiveState/applib>`_ cross-platform utilities
-* `six <http://pypi.python.org/pypi/six/>`_ Python 2 and 3 compatibility utilities
+* `six <https://pypi.org/project/six/>`_ Python 2 and 3 compatibility utilities
 * `pediapress <http://code.pediapress.com/wiki/wiki>`_ MediaWiki articles
-* `mwlib <http://pypi.python.org/pypi/mwlib>`_ mediawiki parser and utility library
+* `mwlib <https://pypi.org/project/mwlib/>`_ mediawiki parser and utility library
 * `The Translate Toolkit <http://translate.sourceforge.net/wiki/toolkit/index>`_ for localization and conversion
 * `execnet <http://codespeak.net/execnet>`_ rapid multi-Python deployment
-* `pylib <http://py.rtfd.org>`_ cross-platform path, IO, dynamic code library
+* `pylib <https://py.readthedocs.io>`_ cross-platform path, IO, dynamic code library
 * `Pacha <http://pacha.cafepais.com/>`_ configuration management in five minutes
-* `bbfreeze <http://pypi.python.org/pypi/bbfreeze>`_ create standalone executables from Python scripts
+* `bbfreeze <https://pypi.org/project/bbfreeze/>`_ create standalone executables from Python scripts
 * `pdb++ <http://bitbucket.org/antocuni/pdb>`_ a fancier version of PDB
 * `py-s3fuse <http://code.google.com/p/py-s3fuse/>`_ Amazon S3 FUSE based filesystem
 * `waskr <http://code.google.com/p/waskr/>`_ WSGI Stats Middleware
 * `guachi <http://code.google.com/p/guachi/>`_ global persistent configs for Python modules
-* `Circuits <http://pypi.python.org/pypi/circuits>`_ lightweight Event Driven Framework
+* `Circuits <https://pypi.org/project/circuits/>`_ lightweight Event Driven Framework
 * `pygtk-helpers <http://bitbucket.org/aafshar/pygtkhelpers-main/>`_ easy interaction with PyGTK
 * `QuantumCore <http://quantumcore.org/>`_ statusmessage and repoze openid plugin
 * `pydataportability <http://pydataportability.net/>`_ libraries for managing the open web
 * `XIST <http://www.livinglogic.de/Python/xist/>`_ extensible HTML/XML generator
-* `tiddlyweb <http://pypi.python.org/pypi/tiddlyweb>`_ optionally headless, extensible RESTful datastore
+* `tiddlyweb <https://pypi.org/project/tiddlyweb/>`_ optionally headless, extensible RESTful datastore
 * `fancycompleter <http://bitbucket.org/antocuni/fancycompleter/src>`_ for colorful tab-completion
 * `Paludis <http://paludis.exherbo.org/>`_ tools for Gentoo Paludis package manager
 * `Gerald <http://halfcooked.com/code/gerald/>`_ schema comparison tool
 * `abjad <http://code.google.com/p/abjad/>`_ Python API for Formalized Score control
 * `bu <http://packages.python.org/bu/>`_ a microscopic build system
 * `katcp <https://bitbucket.org/hodgestar/katcp>`_ Telescope communication protocol over Twisted
-* `kss plugin timer <http://pypi.python.org/pypi/kss.plugin.timer>`_
+* `kss plugin timer <https://pypi.org/project/kss.plugin.timer/>`_
 * `pyudev <https://pyudev.readthedocs.io/en/latest/tests/plugins.html>`_ a pure Python binding to the Linux library libudev
 * `pytest-localserver <https://bitbucket.org/pytest-dev/pytest-localserver/>`_ a plugin for pytest that provides an httpserver and smtpserver
-* `pytest-monkeyplus <http://pypi.python.org/pypi/pytest-monkeyplus/>`_ a plugin that extends monkeypatch
+* `pytest-monkeyplus <https://pypi.org/project/pytest-monkeyplus/>`_ a plugin that extends monkeypatch
 
 These projects help integrate ``pytest`` into other Python frameworks:
 
-* `pytest-django <http://pypi.python.org/pypi/pytest-django/>`_ for Django
+* `pytest-django <https://pypi.org/project/pytest-django/>`_ for Django
 * `zope.pytest <http://packages.python.org/zope.pytest/>`_ for Zope and Grok
-* `pytest_gae <http://pypi.python.org/pypi/pytest_gae/0.2.1>`_ for Google App Engine
+* `pytest_gae <https://pypi.org/project/pytest_gae/0.2.1/>`_ for Google App Engine
 * There is `some work <https://github.com/Kotti/Kotti/blob/master/kotti/testing.py>`_ underway for Kotti, a CMS built in Pyramid/Pylons
 
 
 Some organisations using pytest
 -----------------------------------
 
 * `Square Kilometre Array, Cape Town <http://ska.ac.za/>`_
 * `Some Mozilla QA people <http://www.theautomatedtester.co.uk/blog/2011/pytest_and_xdist_plugin.html>`_ use pytest to distribute their Selenium tests
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/proposals/parametrize_with_fixtures.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/proposals/parametrize_with_fixtures.rst
@@ -30,36 +30,39 @@ emulates user input.
   - specify 'author' and 'project_slug'
 
 This is how a functional test could look like:
 
 .. code-block:: python
 
     import pytest
 
+
     @pytest.fixture
     def default_context():
-        return {'extra_context': {}}
+        return {"extra_context": {}}
 
 
-    @pytest.fixture(params=[
-        {'author': 'alice'},
-        {'project_slug': 'helloworld'},
-        {'author': 'bob', 'project_slug': 'foobar'},
-    ])
+    @pytest.fixture(
+        params=[
+            {"author": "alice"},
+            {"project_slug": "helloworld"},
+            {"author": "bob", "project_slug": "foobar"},
+        ]
+    )
     def extra_context(request):
-        return {'extra_context': request.param}
+        return {"extra_context": request.param}
 
 
-    @pytest.fixture(params=['default', 'extra'])
+    @pytest.fixture(params=["default", "extra"])
     def context(request):
-        if request.param == 'default':
-            return request.getfuncargvalue('default_context')
+        if request.param == "default":
+            return request.getfuncargvalue("default_context")
         else:
-            return request.getfuncargvalue('extra_context')
+            return request.getfuncargvalue("extra_context")
 
 
     def test_generate_project(cookies, context):
         """Call the cookiecutter API to generate a new project from a
         template.
         """
         result = cookies.bake(extra_context=context)
 
@@ -90,18 +93,17 @@ Proposed solution
 -----------------
 
 A new function that can be used in modules can be used to dynamically define
 fixtures from existing ones.
 
 .. code-block:: python
 
     pytest.define_combined_fixture(
-        name='context',
-        fixtures=['default_context', 'extra_context'],
+        name="context", fixtures=["default_context", "extra_context"]
     )
 
 The new fixture ``context`` inherits the scope from the used fixtures and yield
 the following values.
 
 - ``{}``
 
 - ``{'author': 'alice'}``
@@ -113,25 +115,27 @@ the following values.
 Alternative approach
 --------------------
 
 A new helper function named ``fixture_request`` would tell pytest to yield
 all parameters marked as a fixture.
 
 .. note::
 
-    The `pytest-lazy-fixture <https://pypi.python.org/pypi/pytest-lazy-fixture>`_ plugin implements a very
+    The `pytest-lazy-fixture <https://pypi.org/project/pytest-lazy-fixture/>`_ plugin implements a very
     similar solution to the proposal below, make sure to check it out.
 
 .. code-block:: python
 
-    @pytest.fixture(params=[
-        pytest.fixture_request('default_context'),
-        pytest.fixture_request('extra_context'),
-    ])
+    @pytest.fixture(
+        params=[
+            pytest.fixture_request("default_context"),
+            pytest.fixture_request("extra_context"),
+        ]
+    )
     def context(request):
         """Returns all values for ``default_context``, one-by-one before it
         does the same for ``extra_context``.
 
         request.param:
             - {}
             - {'author': 'alice'}
             - {'project_slug': 'helloworld'}
@@ -140,20 +144,20 @@ all parameters marked as a fixture.
         return request.param
 
 The same helper can be used in combination with ``pytest.mark.parametrize``.
 
 .. code-block:: python
 
 
     @pytest.mark.parametrize(
-        'context, expected_response_code',
+        "context, expected_response_code",
         [
-            (pytest.fixture_request('default_context'), 0),
-            (pytest.fixture_request('extra_context'), 0),
+            (pytest.fixture_request("default_context"), 0),
+            (pytest.fixture_request("extra_context"), 0),
         ],
     )
     def test_generate_project(cookies, context, exit_code):
         """Call the cookiecutter API to generate a new project from a
         template.
         """
         result = cookies.bake(extra_context=context)
 
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/reference.rst
@@ -0,0 +1,1296 @@
+
+Reference
+=========
+
+This page contains the full reference to pytest's API.
+
+.. contents::
+    :depth: 3
+    :local:
+
+Functions
+---------
+
+pytest.approx
+~~~~~~~~~~~~~
+
+.. autofunction:: _pytest.python_api.approx
+
+pytest.fail
+~~~~~~~~~~~
+
+**Tutorial**: :ref:`skipping`
+
+.. autofunction:: _pytest.outcomes.fail
+
+pytest.skip
+~~~~~~~~~~~
+
+.. autofunction:: _pytest.outcomes.skip(msg, [allow_module_level=False])
+
+pytest.importorskip
+~~~~~~~~~~~~~~~~~~~
+
+.. autofunction:: _pytest.outcomes.importorskip
+
+pytest.xfail
+~~~~~~~~~~~~
+
+.. autofunction:: _pytest.outcomes.xfail
+
+pytest.exit
+~~~~~~~~~~~
+
+.. autofunction:: _pytest.outcomes.exit
+
+pytest.main
+~~~~~~~~~~~
+
+.. autofunction:: _pytest.config.main
+
+pytest.param
+~~~~~~~~~~~~~
+
+.. autofunction:: pytest.param(*values, [id], [marks])
+
+pytest.raises
+~~~~~~~~~~~~~
+
+**Tutorial**: :ref:`assertraises`.
+
+.. autofunction:: pytest.raises(expected_exception: Exception, [match], [message])
+    :with: excinfo
+
+pytest.deprecated_call
+~~~~~~~~~~~~~~~~~~~~~~
+
+**Tutorial**: :ref:`ensuring_function_triggers`.
+
+.. autofunction:: pytest.deprecated_call()
+    :with:
+
+pytest.register_assert_rewrite
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+**Tutorial**: :ref:`assertion-rewriting`.
+
+.. autofunction:: pytest.register_assert_rewrite
+
+pytest.warns
+~~~~~~~~~~~~
+
+**Tutorial**: :ref:`assertwarnings`
+
+.. autofunction:: pytest.warns(expected_warning: Exception, [match])
+    :with:
+
+
+.. _`marks ref`:
+
+Marks
+-----
+
+Marks can be used apply meta data to *test functions* (but not fixtures), which can then be accessed by
+fixtures or plugins.
+
+
+
+
+.. _`pytest.mark.filterwarnings ref`:
+
+pytest.mark.filterwarnings
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+**Tutorial**: :ref:`filterwarnings`.
+
+Add warning filters to marked test items.
+
+.. py:function:: pytest.mark.filterwarnings(filter)
+
+    :keyword str filter:
+        A *warning specification string*, which is composed of contents of the tuple ``(action, message, category, module, lineno)``
+        as specified in `The Warnings filter <https://docs.python.org/3/library/warnings.html#warning-filter>`_ section of
+        the Python documentation, separated by ``":"``. Optional fields can be omitted.
+
+        For example:
+
+        .. code-block:: python
+
+            @pytest.mark.warnings("ignore:.*usage will be deprecated.*:DeprecationWarning")
+            def test_foo():
+                ...
+
+
+.. _`pytest.mark.parametrize ref`:
+
+pytest.mark.parametrize
+~~~~~~~~~~~~~~~~~~~~~~~
+
+**Tutorial**: :doc:`parametrize`.
+
+.. automethod:: _pytest.python.Metafunc.parametrize
+
+
+.. _`pytest.mark.skip ref`:
+
+pytest.mark.skip
+~~~~~~~~~~~~~~~~
+
+**Tutorial**: :ref:`skip`.
+
+Unconditionally skip a test function.
+
+.. py:function:: pytest.mark.skip(*, reason=None)
+
+    :keyword str reason: Reason why the test function is being skipped.
+
+
+.. _`pytest.mark.skipif ref`:
+
+pytest.mark.skipif
+~~~~~~~~~~~~~~~~~~
+
+**Tutorial**: :ref:`skipif`.
+
+Skip a test function if a condition is ``True``.
+
+.. py:function:: pytest.mark.skipif(condition, *, reason=None)
+
+    :type condition: bool or str
+    :param condition: ``True/False`` if the condition should be skipped or a :ref:`condition string <string conditions>`.
+    :keyword str reason: Reason why the test function is being skipped.
+
+
+.. _`pytest.mark.xfail ref`:
+
+pytest.mark.xfail
+~~~~~~~~~~~~~~~~~~
+
+**Tutorial**: :ref:`xfail`.
+
+Marks a test function as *expected to fail*.
+
+.. py:function:: pytest.mark.xfail(condition=None, *, reason=None, raises=None, run=True, strict=False)
+
+    :type condition: bool or str
+    :param condition: ``True/False`` if the condition should be marked as xfail or a :ref:`condition string <string conditions>`.
+    :keyword str reason: Reason why the test function is marked as xfail.
+    :keyword Exception raises: Exception subclass expected to be raised by the test function; other exceptions will fail the test.
+    :keyword bool run:
+        If the test function should actually be executed. If ``False``, the function will always xfail and will
+        not be executed (useful a function is segfaulting).
+    :keyword bool strict:
+        * If ``False`` (the default) the function will be shown in the terminal output as ``xfailed`` if it fails
+          and as ``xpass`` if it passes. In both cases this will not cause the test suite to fail as a whole. This
+          is particularly useful to mark *flaky* tests (tests that random at fail) to be tackled later.
+        * If ``True``, the function will be shown in the terminal output as ``xfailed`` if it fails, but if it
+          unexpectedly passes then it will **fail** the test suite. This is particularly useful to mark functions
+          that are always failing and there should be a clear indication if they unexpectedly start to pass (for example
+          a new release of a library fixes a known bug).
+
+
+custom marks
+~~~~~~~~~~~~
+
+Marks are created dynamically using the factory object ``pytest.mark`` and applied as a decorator.
+
+For example:
+
+.. code-block:: python
+
+    @pytest.mark.timeout(10, "slow", method="thread")
+    def test_function():
+        ...
+
+Will create and attach a :class:`Mark <_pytest.mark.structures.Mark>` object to the collected
+:class:`Item <_pytest.nodes.Item>`, which can then be accessed by fixtures or hooks with
+:meth:`Node.iter_markers <_pytest.nodes.Node.iter_markers>`. The ``mark`` object will have the following attributes:
+
+.. code-block:: python
+
+    mark.args == (10, "slow")
+    mark.kwargs == {"method": "thread"}
+
+
+Fixtures
+--------
+
+**Tutorial**: :ref:`fixture`.
+
+Fixtures are requested by test functions or other fixtures by declaring them as argument names.
+
+
+Example of a test requiring a fixture:
+
+.. code-block:: python
+
+    def test_output(capsys):
+        print("hello")
+        out, err = capsys.readouterr()
+        assert out == "hello\n"
+
+
+Example of a fixture requiring another fixture:
+
+.. code-block:: python
+
+    @pytest.fixture
+    def db_session(tmpdir):
+        fn = tmpdir / "db.file"
+        return connect(str(fn))
+
+For more details, consult the full :ref:`fixtures docs <fixture>`.
+
+
+@pytest.fixture
+~~~~~~~~~~~~~~~
+
+.. autofunction:: pytest.fixture
+    :decorator:
+
+
+.. _`cache-api`:
+
+config.cache
+~~~~~~~~~~~~
+
+**Tutorial**: :ref:`cache`.
+
+The ``config.cache`` object allows other plugins and fixtures
+to store and retrieve values across test runs. To access it from fixtures
+request ``pytestconfig`` into your fixture and get it with ``pytestconfig.cache``.
+
+Under the hood, the cache plugin uses the simple
+``dumps``/``loads`` API of the :py:mod:`json` stdlib module.
+
+.. currentmodule:: _pytest.cacheprovider
+
+.. automethod:: Cache.get
+.. automethod:: Cache.set
+.. automethod:: Cache.makedir
+
+
+capsys
+~~~~~~
+
+**Tutorial**: :doc:`capture`.
+
+.. currentmodule:: _pytest.capture
+
+.. autofunction:: capsys()
+    :no-auto-options:
+
+    Returns an instance of :py:class:`CaptureFixture`.
+
+    Example:
+
+    .. code-block:: python
+
+        def test_output(capsys):
+            print("hello")
+            captured = capsys.readouterr()
+            assert captured.out == "hello\n"
+
+.. autoclass:: CaptureFixture()
+    :members:
+
+
+capsysbinary
+~~~~~~~~~~~~
+
+**Tutorial**: :doc:`capture`.
+
+.. autofunction:: capsysbinary()
+    :no-auto-options:
+
+    Returns an instance of :py:class:`CaptureFixture`.
+
+    Example:
+
+    .. code-block:: python
+
+        def test_output(capsysbinary):
+            print("hello")
+            captured = capsysbinary.readouterr()
+            assert captured.out == b"hello\n"
+
+
+capfd
+~~~~~~
+
+**Tutorial**: :doc:`capture`.
+
+.. autofunction:: capfd()
+    :no-auto-options:
+
+    Returns an instance of :py:class:`CaptureFixture`.
+
+    Example:
+
+    .. code-block:: python
+
+        def test_system_echo(capfd):
+            os.system('echo "hello"')
+            captured = capsys.readouterr()
+            assert captured.out == "hello\n"
+
+
+capfdbinary
+~~~~~~~~~~~~
+
+**Tutorial**: :doc:`capture`.
+
+.. autofunction:: capfdbinary()
+    :no-auto-options:
+
+    Returns an instance of :py:class:`CaptureFixture`.
+
+    Example:
+
+    .. code-block:: python
+
+        def test_system_echo(capfdbinary):
+            os.system('echo "hello"')
+            captured = capfdbinary.readouterr()
+            assert captured.out == b"hello\n"
+
+
+doctest_namespace
+~~~~~~~~~~~~~~~~~
+
+**Tutorial**: :doc:`doctest`.
+
+.. autofunction:: _pytest.doctest.doctest_namespace()
+
+    Usually this fixture is used in conjunction with another ``autouse`` fixture:
+
+    .. code-block:: python
+
+        @pytest.fixture(autouse=True)
+        def add_np(doctest_namespace):
+            doctest_namespace["np"] = numpy
+
+    For more details: :ref:`doctest_namespace`.
+
+
+request
+~~~~~~~
+
+**Tutorial**: :ref:`request example`.
+
+The ``request`` fixture is a special fixture providing information of the requesting test function.
+
+.. autoclass:: _pytest.fixtures.FixtureRequest()
+    :members:
+
+
+pytestconfig
+~~~~~~~~~~~~
+
+.. autofunction:: _pytest.fixtures.pytestconfig()
+
+
+record_property
+~~~~~~~~~~~~~~~~~~~
+
+**Tutorial**: :ref:`record_property example`.
+
+.. autofunction:: _pytest.junitxml.record_property()
+
+caplog
+~~~~~~
+
+**Tutorial**: :doc:`logging`.
+
+.. autofunction:: _pytest.logging.caplog()
+    :no-auto-options:
+
+    This returns a :class:`_pytest.logging.LogCaptureFixture` instance.
+
+.. autoclass:: _pytest.logging.LogCaptureFixture
+    :members:
+
+
+monkeypatch
+~~~~~~~~~~~
+
+.. currentmodule:: _pytest.monkeypatch
+
+**Tutorial**: :doc:`monkeypatch`.
+
+.. autofunction:: _pytest.monkeypatch.monkeypatch()
+    :no-auto-options:
+
+    This returns a :class:`MonkeyPatch` instance.
+
+.. autoclass:: _pytest.monkeypatch.MonkeyPatch
+    :members:
+
+testdir
+~~~~~~~
+
+.. currentmodule:: _pytest.pytester
+
+This fixture provides a :class:`Testdir` instance useful for black-box testing of test files, making it ideal to
+test plugins.
+
+To use it, include in your top-most ``conftest.py`` file::
+
+    pytest_plugins = 'pytester'
+
+
+
+.. autoclass:: Testdir()
+    :members: runpytest,runpytest_subprocess,runpytest_inprocess,makeconftest,makepyfile
+
+.. autoclass:: RunResult()
+    :members:
+
+.. autoclass:: LineMatcher()
+    :members:
+
+
+recwarn
+~~~~~~~
+
+**Tutorial**: :ref:`assertwarnings`
+
+.. currentmodule:: _pytest.recwarn
+
+.. autofunction:: recwarn()
+    :no-auto-options:
+
+.. autoclass:: _pytest.recwarn.WarningsRecorder()
+    :members:
+
+Each recorded warning is an instance of :class:`warnings.WarningMessage`.
+
+.. note::
+    :class:`RecordedWarning` was changed from a plain class to a namedtuple in pytest 3.1
+
+.. note::
+    ``DeprecationWarning`` and ``PendingDeprecationWarning`` are treated
+    differently; see :ref:`ensuring_function_triggers`.
+
+
+tmpdir
+~~~~~~
+
+**Tutorial**: :doc:`tmpdir`
+
+.. currentmodule:: _pytest.tmpdir
+
+.. autofunction:: tmpdir()
+    :no-auto-options:
+
+
+tmpdir_factory
+~~~~~~~~~~~~~~
+
+**Tutorial**: :ref:`tmpdir factory example`
+
+.. _`tmpdir factory api`:
+
+``tmpdir_factory`` instances have the following methods:
+
+.. currentmodule:: _pytest.tmpdir
+
+.. automethod:: TempdirFactory.mktemp
+.. automethod:: TempdirFactory.getbasetemp
+
+
+.. _`hook-reference`:
+
+Hooks
+-----
+
+**Tutorial**: :doc:`writing_plugins`.
+
+.. currentmodule:: _pytest.hookspec
+
+Reference to all hooks which can be implemented by :ref:`conftest.py files <localplugin>` and :ref:`plugins <plugins>`.
+
+Bootstrapping hooks
+~~~~~~~~~~~~~~~~~~~
+
+Bootstrapping hooks called for plugins registered early enough (internal and setuptools plugins).
+
+.. autofunction:: pytest_load_initial_conftests
+.. autofunction:: pytest_cmdline_preparse
+.. autofunction:: pytest_cmdline_parse
+.. autofunction:: pytest_cmdline_main
+
+Initialization hooks
+~~~~~~~~~~~~~~~~~~~~
+
+Initialization hooks called for plugins and ``conftest.py`` files.
+
+.. autofunction:: pytest_addoption
+.. autofunction:: pytest_addhooks
+.. autofunction:: pytest_configure
+.. autofunction:: pytest_unconfigure
+.. autofunction:: pytest_sessionstart
+.. autofunction:: pytest_sessionfinish
+
+Test running hooks
+~~~~~~~~~~~~~~~~~~
+
+All runtest related hooks receive a :py:class:`pytest.Item <_pytest.main.Item>` object.
+
+.. autofunction:: pytest_runtestloop
+.. autofunction:: pytest_runtest_protocol
+.. autofunction:: pytest_runtest_logstart
+.. autofunction:: pytest_runtest_logfinish
+.. autofunction:: pytest_runtest_setup
+.. autofunction:: pytest_runtest_call
+.. autofunction:: pytest_runtest_teardown
+.. autofunction:: pytest_runtest_makereport
+
+For deeper understanding you may look at the default implementation of
+these hooks in :py:mod:`_pytest.runner` and maybe also
+in :py:mod:`_pytest.pdb` which interacts with :py:mod:`_pytest.capture`
+and its input/output capturing in order to immediately drop
+into interactive debugging when a test failure occurs.
+
+The :py:mod:`_pytest.terminal` reported specifically uses
+the reporting hook to print information about a test run.
+
+Collection hooks
+~~~~~~~~~~~~~~~~
+
+``pytest`` calls the following hooks for collecting files and directories:
+
+.. autofunction:: pytest_collection
+.. autofunction:: pytest_ignore_collect
+.. autofunction:: pytest_collect_directory
+.. autofunction:: pytest_collect_file
+
+For influencing the collection of objects in Python modules
+you can use the following hook:
+
+.. autofunction:: pytest_pycollect_makeitem
+.. autofunction:: pytest_generate_tests
+.. autofunction:: pytest_make_parametrize_id
+
+After collection is complete, you can modify the order of
+items, delete or otherwise amend the test items:
+
+.. autofunction:: pytest_collection_modifyitems
+
+Reporting hooks
+~~~~~~~~~~~~~~~
+
+Session related reporting hooks:
+
+.. autofunction:: pytest_collectstart
+.. autofunction:: pytest_itemcollected
+.. autofunction:: pytest_collectreport
+.. autofunction:: pytest_deselected
+.. autofunction:: pytest_report_header
+.. autofunction:: pytest_report_collectionfinish
+.. autofunction:: pytest_report_teststatus
+.. autofunction:: pytest_terminal_summary
+.. autofunction:: pytest_fixture_setup
+.. autofunction:: pytest_fixture_post_finalizer
+
+And here is the central hook for reporting about
+test execution:
+
+.. autofunction:: pytest_runtest_logreport
+
+You can also use this hook to customize assertion representation for some
+types:
+
+.. autofunction:: pytest_assertrepr_compare
+
+
+Debugging/Interaction hooks
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+There are few hooks which can be used for special
+reporting or interaction with exceptions:
+
+.. autofunction:: pytest_internalerror
+.. autofunction:: pytest_keyboard_interrupt
+.. autofunction:: pytest_exception_interact
+.. autofunction:: pytest_enter_pdb
+
+
+Objects
+-------
+
+Full reference to objects accessible from :ref:`fixtures <fixture>` or :ref:`hooks <hook-reference>`.
+
+
+CallInfo
+~~~~~~~~
+
+.. autoclass:: _pytest.runner.CallInfo()
+    :members:
+
+
+Class
+~~~~~
+
+.. autoclass:: _pytest.python.Class()
+    :members:
+    :show-inheritance:
+
+Collector
+~~~~~~~~~
+
+.. autoclass:: _pytest.nodes.Collector()
+    :members:
+    :show-inheritance:
+
+Config
+~~~~~~
+
+.. autoclass:: _pytest.config.Config()
+    :members:
+
+ExceptionInfo
+~~~~~~~~~~~~~
+
+.. autoclass:: _pytest._code.ExceptionInfo
+    :members:
+
+FixtureDef
+~~~~~~~~~~
+
+.. autoclass:: _pytest.fixtures.FixtureDef()
+    :members:
+    :show-inheritance:
+
+FSCollector
+~~~~~~~~~~~
+
+.. autoclass:: _pytest.nodes.FSCollector()
+    :members:
+    :show-inheritance:
+
+Function
+~~~~~~~~
+
+.. autoclass:: _pytest.python.Function()
+    :members:
+    :show-inheritance:
+
+Item
+~~~~
+
+.. autoclass:: _pytest.nodes.Item()
+    :members:
+    :show-inheritance:
+
+MarkDecorator
+~~~~~~~~~~~~~
+
+.. autoclass:: _pytest.mark.MarkDecorator
+    :members:
+
+
+MarkGenerator
+~~~~~~~~~~~~~
+
+.. autoclass:: _pytest.mark.MarkGenerator
+    :members:
+
+
+MarkInfo
+~~~~~~~~
+
+.. autoclass:: _pytest.mark.MarkInfo
+    :members:
+
+
+Mark
+~~~~
+
+.. autoclass:: _pytest.mark.structures.Mark
+    :members:
+
+
+Metafunc
+~~~~~~~~
+
+.. autoclass:: _pytest.python.Metafunc
+    :members:
+
+Module
+~~~~~~
+
+.. autoclass:: _pytest.python.Module()
+    :members:
+    :show-inheritance:
+
+Node
+~~~~
+
+.. autoclass:: _pytest.nodes.Node()
+    :members:
+
+Parser
+~~~~~~
+
+.. autoclass:: _pytest.config.argparsing.Parser()
+    :members:
+
+PluginManager
+~~~~~~~~~~~~~
+
+.. autoclass:: pluggy.PluginManager()
+    :members:
+
+
+PytestPluginManager
+~~~~~~~~~~~~~~~~~~~
+
+.. autoclass:: _pytest.config.PytestPluginManager()
+    :members:
+    :undoc-members:
+    :show-inheritance:
+
+Session
+~~~~~~~
+
+.. autoclass:: _pytest.main.Session()
+    :members:
+    :show-inheritance:
+
+TestReport
+~~~~~~~~~~
+
+.. autoclass:: _pytest.runner.TestReport()
+    :members:
+    :inherited-members:
+
+_Result
+~~~~~~~
+
+.. autoclass:: pluggy._Result
+    :members:
+
+Special Variables
+-----------------
+
+pytest treats some global variables in a special manner when defined in a test module.
+
+
+pytest_plugins
+~~~~~~~~~~~~~~
+
+**Tutorial**: :ref:`available installable plugins`
+
+Can be declared at the **global** level in *test modules* and *conftest.py files* to register additional plugins.
+Can be either a ``str`` or ``Sequence[str]``.
+
+.. code-block:: python
+
+    pytest_plugins = "myapp.testsupport.myplugin"
+
+.. code-block:: python
+
+    pytest_plugins = ("myapp.testsupport.tools", "myapp.testsupport.regression")
+
+
+pytest_mark
+~~~~~~~~~~~
+
+**Tutorial**: :ref:`scoped-marking`
+
+Can be declared at the **global** level in *test modules* to apply one or more :ref:`marks <marks ref>` to all
+test functions and methods. Can be either a single mark or a sequence of marks.
+
+.. code-block:: python
+
+    import pytest
+
+    pytestmark = pytest.mark.webtest
+
+
+.. code-block:: python
+
+    import pytest
+
+    pytestmark = (pytest.mark.integration, pytest.mark.slow)
+
+PYTEST_DONT_REWRITE (module docstring)
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The text ``PYTEST_DONT_REWRITE`` can be add to any **module docstring** to disable
+:ref:`assertion rewriting <assert introspection>` for that module.
+
+
+Environment Variables
+---------------------
+
+Environment variables that can be used to change pytest's behavior.
+
+PYTEST_ADDOPTS
+~~~~~~~~~~~~~~
+
+This contains a command-line (parsed by the py:mod:`shlex` module) that will be **prepended** to the command line given
+by the user, see :ref:`adding default options` for more information.
+
+PYTEST_DEBUG
+~~~~~~~~~~~~
+
+When set, pytest will print tracing and debug information.
+
+PYTEST_PLUGINS
+~~~~~~~~~~~~~~
+
+Contains comma-separated list of modules that should be loaded as plugins:
+
+.. code-block:: bash
+
+    export PYTEST_PLUGINS=mymodule.plugin,xdist
+
+
+PYTEST_CURRENT_TEST
+~~~~~~~~~~~~~~~~~~~
+
+This is not meant to be set by users, but is set by pytest internally with the name of the current test so other
+processes can inspect it, see :ref:`pytest current test env` for more information.
+
+
+.. _`ini options ref`:
+
+Configuration Options
+---------------------
+
+Here is a list of builtin configuration options that may be written in a ``pytest.ini``, ``tox.ini`` or ``setup.cfg``
+file, usually located at the root of your repository. All options must be under a ``[pytest]`` section
+(``[tool:pytest]`` for ``setup.cfg`` files).
+
+Configuration file options may be overwritten in the command-line by using ``-o/--override``, which can also be
+passed multiple times. The expected format is ``name=value``. For example::
+
+   pytest -o console_output_style=classic -o cache_dir=/tmp/mycache
+
+
+.. confval:: addopts
+
+   Add the specified ``OPTS`` to the set of command line arguments as if they
+   had been specified by the user. Example: if you have this ini file content:
+
+   .. code-block:: ini
+
+        # content of pytest.ini
+        [pytest]
+        addopts = --maxfail=2 -rf  # exit after 2 failures, report fail info
+
+   issuing ``pytest test_hello.py`` actually means::
+
+        pytest --maxfail=2 -rf test_hello.py
+
+   Default is to add no options.
+
+
+.. confval:: cache_dir
+
+   .. versionadded:: 3.2
+
+   Sets a directory where stores content of cache plugin. Default directory is
+   ``.pytest_cache`` which is created in :ref:`rootdir <rootdir>`. Directory may be
+   relative or absolute path. If setting relative path, then directory is created
+   relative to :ref:`rootdir <rootdir>`. Additionally path may contain environment
+   variables, that will be expanded. For more information about cache plugin
+   please refer to :ref:`cache_provider`.
+
+
+.. confval:: confcutdir
+
+   Sets a directory where search upwards for ``conftest.py`` files stops.
+   By default, pytest will stop searching for ``conftest.py`` files upwards
+   from ``pytest.ini``/``tox.ini``/``setup.cfg`` of the project if any,
+   or up to the file-system root.
+
+
+.. confval:: console_output_style
+
+   .. versionadded:: 3.3
+
+   Sets the console output style while running tests:
+
+   * ``classic``: classic pytest output.
+   * ``progress``: like classic pytest output, but with a progress indicator.
+
+   The default is ``progress``, but you can fallback to ``classic`` if you prefer or
+   the new mode is causing unexpected problems:
+
+   .. code-block:: ini
+
+        # content of pytest.ini
+        [pytest]
+        console_output_style = classic
+
+
+.. confval:: doctest_encoding
+
+   .. versionadded:: 3.1
+
+   Default encoding to use to decode text files with docstrings.
+   :doc:`See how pytest handles doctests <doctest>`.
+
+
+.. confval:: doctest_optionflags
+
+   One or more doctest flag names from the standard ``doctest`` module.
+   :doc:`See how pytest handles doctests <doctest>`.
+
+
+.. confval:: empty_parameter_set_mark
+
+    .. versionadded:: 3.4
+
+    Allows to pick the action for empty parametersets in parameterization
+
+    * ``skip`` skips tests with an empty parameterset (default)
+    * ``xfail`` marks tests with an empty parameterset as xfail(run=False)
+
+    .. code-block:: ini
+
+      # content of pytest.ini
+      [pytest]
+      empty_parameter_set_mark = xfail
+
+    .. note::
+
+      The default value of this option is planned to change to ``xfail`` in future releases
+      as this is considered less error prone, see `#3155 <https://github.com/pytest-dev/pytest/issues/3155>`_
+      for more details.
+
+
+.. confval:: filterwarnings
+
+   .. versionadded:: 3.1
+
+   Sets a list of filters and actions that should be taken for matched
+   warnings. By default all warnings emitted during the test session
+   will be displayed in a summary at the end of the test session.
+
+   .. code-block:: ini
+
+        # content of pytest.ini
+        [pytest]
+        filterwarnings =
+            error
+            ignore::DeprecationWarning
+
+   This tells pytest to ignore deprecation warnings and turn all other warnings
+   into errors. For more information please refer to :ref:`warnings`.
+
+
+.. confval:: junit_suite_name
+
+    .. versionadded:: 3.1
+
+    To set the name of the root test suite xml item, you can configure the ``junit_suite_name`` option in your config file:
+
+    .. code-block:: ini
+
+        [pytest]
+        junit_suite_name = my_suite
+
+
+.. confval:: log_cli_date_format
+
+    .. versionadded:: 3.3
+
+    Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for live logging.
+
+    .. code-block:: ini
+
+        [pytest]
+        log_cli_date_format = %Y-%m-%d %H:%M:%S
+
+    For more information, see :ref:`live_logs`.
+
+.. confval:: log_cli_format
+
+    .. versionadded:: 3.3
+
+    Sets a :py:mod:`logging`-compatible string used to format live logging messages.
+
+    .. code-block:: ini
+
+        [pytest]
+        log_cli_format = %(asctime)s %(levelname)s %(message)s
+
+    For more information, see :ref:`live_logs`.
+
+
+.. confval:: log_cli_level
+
+    .. versionadded:: 3.3
+
+    Sets the minimum log message level that should be captured for live logging. The integer value or
+    the names of the levels can be used.
+
+    .. code-block:: ini
+
+        [pytest]
+        log_cli_level = INFO
+
+    For more information, see :ref:`live_logs`.
+
+
+.. confval:: log_date_format
+
+    .. versionadded:: 3.3
+
+    Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for logging capture.
+
+    .. code-block:: ini
+
+        [pytest]
+        log_date_format = %Y-%m-%d %H:%M:%S
+
+    For more information, see :ref:`logging`.
+
+
+.. confval:: log_file
+
+    .. versionadded:: 3.3
+
+    Sets a file name relative to the ``pytest.ini`` file where log messages should be written to, in addition
+    to the other logging facilities that are active.
+
+    .. code-block:: ini
+
+        [pytest]
+        log_file = logs/pytest-logs.txt
+
+    For more information, see :ref:`logging`.
+
+
+.. confval:: log_file_date_format
+
+    .. versionadded:: 3.3
+
+    Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for the logging file.
+
+    .. code-block:: ini
+
+        [pytest]
+        log_file_date_format = %Y-%m-%d %H:%M:%S
+
+    For more information, see :ref:`logging`.
+
+.. confval:: log_file_format
+
+    .. versionadded:: 3.3
+
+    Sets a :py:mod:`logging`-compatible string used to format logging messages redirected to the logging file.
+
+    .. code-block:: ini
+
+        [pytest]
+        log_file_format = %(asctime)s %(levelname)s %(message)s
+
+    For more information, see :ref:`logging`.
+
+.. confval:: log_file_level
+
+    .. versionadded:: 3.3
+
+    Sets the minimum log message level that should be captured for the logging file. The integer value or
+    the names of the levels can be used.
+
+    .. code-block:: ini
+
+        [pytest]
+        log_file_level = INFO
+
+    For more information, see :ref:`logging`.
+
+
+.. confval:: log_format
+
+    .. versionadded:: 3.3
+
+    Sets a :py:mod:`logging`-compatible string used to format captured logging messages.
+
+    .. code-block:: ini
+
+        [pytest]
+        log_format = %(asctime)s %(levelname)s %(message)s
+
+    For more information, see :ref:`logging`.
+
+
+.. confval:: log_level
+
+    .. versionadded:: 3.3
+
+    Sets the minimum log message level that should be captured for logging capture. The integer value or
+    the names of the levels can be used.
+
+    .. code-block:: ini
+
+        [pytest]
+        log_level = INFO
+
+    For more information, see :ref:`logging`.
+
+
+.. confval:: log_print
+
+    .. versionadded:: 3.3
+
+    If set to ``False``, will disable displaying captured logging messages for failed tests.
+
+    .. code-block:: ini
+
+        [pytest]
+        log_print = False
+
+    For more information, see :ref:`logging`.
+
+
+.. confval:: markers
+
+    List of markers that are allowed in test functions, enforced when ``--strict`` command-line argument is used.
+    You can use a marker name per line, indented from the option name.
+
+    .. code-block:: ini
+
+        [pytest]
+        markers =
+            slow
+            serial
+
+.. confval:: minversion
+
+   Specifies a minimal pytest version required for running tests.
+
+   .. code-block:: ini
+
+        # content of pytest.ini
+        [pytest]
+        minversion = 3.0  # will fail if we run with pytest-2.8
+
+
+.. confval:: norecursedirs
+
+   Set the directory basename patterns to avoid when recursing
+   for test discovery.  The individual (fnmatch-style) patterns are
+   applied to the basename of a directory to decide if to recurse into it.
+   Pattern matching characters::
+
+        *       matches everything
+        ?       matches any single character
+        [seq]   matches any character in seq
+        [!seq]  matches any char not in seq
+
+   Default patterns are ``'.*', 'build', 'dist', 'CVS', '_darcs', '{arch}', '*.egg', 'venv'``.
+   Setting a ``norecursedirs`` replaces the default.  Here is an example of
+   how to avoid certain directories:
+
+   .. code-block:: ini
+
+        [pytest]
+        norecursedirs = .svn _build tmp*
+
+   This would tell ``pytest`` to not look into typical subversion or
+   sphinx-build directories or into any ``tmp`` prefixed directory.
+
+   Additionally, ``pytest`` will attempt to intelligently identify and ignore a
+   virtualenv by the presence of an activation script.  Any directory deemed to
+   be the root of a virtual environment will not be considered during test
+   collection unless ``‑‑collect‑in‑virtualenv`` is given.  Note also that
+   ``norecursedirs`` takes precedence over ``‑‑collect‑in‑virtualenv``; e.g. if
+   you intend to run tests in a virtualenv with a base directory that matches
+   ``'.*'`` you *must* override ``norecursedirs`` in addition to using the
+   ``‑‑collect‑in‑virtualenv`` flag.
+
+
+.. confval:: python_classes
+
+   One or more name prefixes or glob-style patterns determining which classes
+   are considered for test collection. By default, pytest will consider any
+   class prefixed with ``Test`` as a test collection.  Here is an example of how
+   to collect tests from classes that end in ``Suite``:
+
+   .. code-block:: ini
+
+        [pytest]
+        python_classes = *Suite
+
+   Note that ``unittest.TestCase`` derived classes are always collected
+   regardless of this option, as ``unittest``'s own collection framework is used
+   to collect those tests.
+
+
+.. confval:: python_files
+
+   One or more Glob-style file patterns determining which python files
+   are considered as test modules. By default, pytest will consider
+   any file matching with ``test_*.py`` and ``*_test.py`` globs as a test
+   module.
+
+
+.. confval:: python_functions
+
+   One or more name prefixes or glob-patterns determining which test functions
+   and methods are considered tests. By default, pytest will consider any
+   function prefixed with ``test`` as a test.  Here is an example of how
+   to collect test functions and methods that end in ``_test``:
+
+   .. code-block:: ini
+
+        [pytest]
+        python_functions = *_test
+
+   Note that this has no effect on methods that live on a ``unittest
+   .TestCase`` derived class, as ``unittest``'s own collection framework is used
+   to collect those tests.
+
+   See :ref:`change naming conventions` for more detailed examples.
+
+
+.. confval:: testpaths
+
+   .. versionadded:: 2.8
+
+   Sets list of directories that should be searched for tests when
+   no specific directories, files or test ids are given in the command line when
+   executing pytest from the :ref:`rootdir <rootdir>` directory.
+   Useful when all project tests are in a known location to speed up
+   test collection and to avoid picking up undesired tests by accident.
+
+   .. code-block:: ini
+
+        [pytest]
+        testpaths = testing doc
+
+   This tells pytest to only look for tests in ``testing`` and ``doc``
+   directories when executing from the root directory.
+
+
+.. confval:: usefixtures
+
+    List of fixtures that will be applied to all test functions; this is semantically the same to apply
+    the ``@pytest.mark.usefixtures`` marker to all test functions.
+
+
+    .. code-block:: ini
+
+        [pytest]
+        usefixtures =
+            clean_db
+
+
+.. confval:: xfail_strict
+
+    If set to ``True``, tests marked with ``@pytest.mark.xfail`` that actually succeed will by default fail the
+    test suite.
+    For more information, see :ref:`xfail strict tutorial`.
+
+
+    .. code-block:: ini
+
+        [pytest]
+        xfail_strict = True
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/requirements.txt
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/requirements.txt
@@ -1,3 +1,4 @@
 # pinning sphinx to 1.4.* due to search issues with rtd:
 # https://github.com/rtfd/readthedocs-sphinx-ext/issues/25
 sphinx ==1.4.*
+sphinxcontrib-trio
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/skipping.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/skipping.rst
@@ -66,16 +66,18 @@ It is also possible to skip the whole mo
     import pytest
 
     if not pytest.config.getoption("--custom-flag"):
         pytest.skip("--custom-flag is missing, skipping tests", allow_module_level=True)
 
 The imperative method is useful when it is not possible to evaluate the skip condition
 during import time.
 
+**Reference**: :ref:`pytest.mark.skip ref`
+
 ``skipif``
 ~~~~~~~~~~
 
 .. versionadded:: 2.0
 
 If you wish to skip something conditionally then you can use ``skipif`` instead.
 Here is an example of marking a test function to be skipped
 when run on a Python3.6 interpreter::
@@ -111,16 +113,18 @@ You can import the marker and reuse it i
 For larger test suites it's usually a good idea to have one file
 where you define the markers which you then consistently apply
 throughout your test suite.
 
 Alternatively, you can use :ref:`condition strings
 <string conditions>` instead of booleans, but they can't be shared between modules easily
 so they are supported mainly for backward compatibility reasons.
 
+**Reference**: :ref:`pytest.mark.skipif ref`
+
 
 Skip all test functions of a class or module
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
 You can use the ``skipif`` marker (as any other marker) on classes::
 
     @pytest.mark.skipif(sys.platform == 'win32',
                         reason="does not run on windows")
@@ -183,29 +187,29 @@ Summary
 ~~~~~~~
 
 Here's a quick guide on how to skip tests in a module in different situations:
 
 1. Skip all tests in a module unconditionally:
 
   .. code-block:: python
 
-        pytestmark = pytest.mark.skip('all tests still WIP')
+        pytestmark = pytest.mark.skip("all tests still WIP")
 
 2. Skip all tests in a module based on some condition:
 
   .. code-block:: python
 
-        pytestmark = pytest.mark.skipif(sys.platform == 'win32', 'tests for linux only')
+        pytestmark = pytest.mark.skipif(sys.platform == "win32", "tests for linux only")
 
 3. Skip all tests in a module if some import is missing:
 
   .. code-block:: python
 
-        pexpect = pytest.importorskip('pexpect')
+        pexpect = pytest.importorskip("pexpect")
 
 
 .. _xfail:
 
 XFail: mark test functions as expected to fail
 ----------------------------------------------
 
 You can use the ``xfail`` marker to indicate that you
@@ -227,25 +231,20 @@ imperatively:
     def test_function():
         if not valid_config():
             pytest.xfail("failing configuration (but should work)")
 
 This will unconditionally make ``test_function`` ``XFAIL``. Note that no other code is executed
 after ``pytest.xfail`` call, differently from the marker. That's because it is implemented
 internally by raising a known exception.
 
-Here's the signature of the ``xfail`` **marker** (not the function), using Python 3 keyword-only
-arguments syntax:
-
-.. code-block:: python
-
-    def xfail(condition=None, *, reason=None, raises=None, run=True, strict=False):
+**Reference**: :ref:`pytest.mark.xfail ref`
 
 
-
+.. _`xfail strict tutorial`:
 
 ``strict`` parameter
 ~~~~~~~~~~~~~~~~~~~~
 
 .. versionadded:: 2.9
 
 Both ``XFAIL`` and ``XPASS`` don't fail the test suite, unless the ``strict`` keyword-only
 parameter is passed as ``True``:
@@ -330,49 +329,55 @@ Here is a simple test file with the seve
 
 Running it with the report-on-xfail option gives this output::
 
     example $ pytest -rx xfail_demo.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR/example, inifile:
     collected 7 items
-    
+
     xfail_demo.py xxxxxxx                                                [100%]
     ========================= short test summary info ==========================
     XFAIL xfail_demo.py::test_hello
     XFAIL xfail_demo.py::test_hello2
-      reason: [NOTRUN] 
+      reason: [NOTRUN]
     XFAIL xfail_demo.py::test_hello3
       condition: hasattr(os, 'sep')
     XFAIL xfail_demo.py::test_hello4
       bug 110
     XFAIL xfail_demo.py::test_hello5
       condition: pytest.__version__[0] != "17"
     XFAIL xfail_demo.py::test_hello6
       reason: reason
     XFAIL xfail_demo.py::test_hello7
-    
+
     ======================== 7 xfailed in 0.12 seconds =========================
 
 .. _`skip/xfail with parametrize`:
 
 Skip/xfail with parametrize
 ---------------------------
 
 It is possible to apply markers like skip and xfail to individual
 test instances when using parametrize:
 
 .. code-block:: python
 
     import pytest
 
-    @pytest.mark.parametrize(("n", "expected"), [
-        (1, 2),
-    pytest.param(1, 0, marks=pytest.mark.xfail),
-	pytest.param(1, 3, marks=pytest.mark.xfail(reason="some bug")),
-        (2, 3),
-        (3, 4),
-        (4, 5),
-    pytest.param(10, 11, marks=pytest.mark.skipif(sys.version_info >= (3, 0), reason="py2k")),
-    ])
+
+    @pytest.mark.parametrize(
+        ("n", "expected"),
+        [
+            (1, 2),
+            pytest.param(1, 0, marks=pytest.mark.xfail),
+            pytest.param(1, 3, marks=pytest.mark.xfail(reason="some bug")),
+            (2, 3),
+            (3, 4),
+            (4, 5),
+            pytest.param(
+                10, 11, marks=pytest.mark.skipif(sys.version_info >= (3, 0), reason="py2k")
+            ),
+        ],
+    )
     def test_increment(n, expected):
         assert n + 1 == expected
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/talks.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/talks.rst
@@ -93,13 +93,8 @@ Plugin specific examples:
 .. _`monkeypatch plugin`: monkeypatch.html
 .. _`application setup in test functions with fixtures`: fixture.html#interdependent-fixtures
 .. _`simultaneously test your code on all platforms`: http://tetamap.wordpress.com/2009/03/23/new-simultanously-test-your-code-on-all-platforms/
 .. _`monkey patching done right`: http://tetamap.wordpress.com/2009/03/03/monkeypatching-in-unit-tests-done-right/
 .. _`putting test-hooks into local or global plugins`: http://tetamap.wordpress.com/2009/05/14/putting-test-hooks-into-local-and-global-plugins/
 .. _`parametrizing tests, generalized`: http://tetamap.wordpress.com/2009/05/13/parametrizing-python-tests-generalized/
 .. _`generating parametrized tests with fixtures`: parametrize.html#test-generators
 .. _`test generators and cached setup`: http://bruynooghe.blogspot.com/2010/06/pytest-test-generators-and-cached-setup.html
-
-
-
-
-
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/attic.rst
+++ /dev/null
@@ -1,117 +0,0 @@
-===============================================
-ATTIC documentation
-===============================================
-
-XXX REVIEW and remove the below  XXX
-
-Customizing the testing process
-===============================
-
-writing conftest.py files
------------------------------------
-
-You may put conftest.py files containing project-specific
-configuration in your project's root directory, it's usually
-best to put it just into the same directory level as your
-topmost ``__init__.py``.  In fact, ``pytest`` performs
-an "upwards" search starting from the directory that you specify
-to be tested and will lookup configuration values right-to-left.
-You may have options that reside e.g. in your home directory
-but note that project specific settings will be considered
-first.  There is a flag that helps you debugging your
-conftest.py configurations::
-
-    pytest --trace-config
-
-
-customizing the collecting and running process
------------------------------------------------
-
-To introduce different test items you can create
-one or more ``conftest.py`` files in your project.
-When the collection process traverses directories
-and modules the default collectors will produce
-custom Collectors and Items if they are found
-in a local ``conftest.py`` file.
-
-
-Customizing the collection process in a module
-----------------------------------------------
-
-If you have a module where you want to take responsibility for
-collecting your own test Items and possibly even for executing
-a test then you can provide `generative tests`_ that yield
-callables and possibly arguments as a tuple.   This is especially
-useful for calling application test machinery with different
-parameter sets but counting each of the calls as a separate
-tests.
-
-.. _`generative tests`: features.html#generative-tests
-
-The other extension possibility is about
-specifying a custom test ``Item`` class which
-is responsible for setting up and executing an underlying
-test.  Or you can extend the collection process for a whole
-directory tree by putting Items in a ``conftest.py`` configuration file.
-The collection process dynamically consults the *chain of conftest.py*
-modules to determine collectors and items at ``Directory``, ``Module``,
-``Class``, ``Function`` or ``Generator`` level respectively.
-
-Customizing execution of Items and Functions
-----------------------------------------------------
-
-- ``pytest.Function`` test items control execution
-  of a test function through its ``function.runtest()`` method.
-  This method is responsible for performing setup and teardown
-  ("Test Fixtures") for a test Function.
-
-- ``Function.execute(target, *args)`` methods are invoked by
-  the default ``Function.run()`` to actually execute a python
-  function with the given (usually empty set of) arguments.
-
-.. _`py-dev mailing list`: http://codespeak.net/mailman/listinfo/py-dev
-
-
-.. _`test generators`: funcargs.html#test-generators
-
-.. _`generative tests`:
-
-generative tests: yielding parametrized tests
-====================================================
-
-Deprecated since 1.0 in favour of `test generators`_.
-
-*Generative tests* are test methods that are *generator functions* which
-``yield`` callables and their arguments.  This is useful for running a
-test function multiple times against different parameters.  Example::
-
-    def test_generative():
-        for x in (42,17,49):
-            yield check, x
-
-    def check(arg):
-        assert arg % 7 == 0   # second generated tests fails!
-
-Note that ``test_generative()`` will cause three tests
-to get run, notably ``check(42)``, ``check(17)`` and ``check(49)``
-of which the middle one will obviously fail.
-
-To make it easier to distinguish the generated tests it is possible to specify an explicit name for them, like for example::
-
-    def test_generative():
-        for x in (42,17,49):
-            yield "case %d" % x, check, x
-
-
-disabling a test class
-----------------------
-
-If you want to disable a complete test class you
-can set the class-level attribute ``disabled``.
-For example, in order to avoid running some tests on Win32::
-
-    class TestPosixOnly(object):
-        disabled = sys.platform == 'win32'
-
-        def test_xxx(self):
-            ...
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/config.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<html>
-    <head>
-        <meta http-equiv="refresh" content=" 1 ; URL=customize.html" />
-    </head>
-
-    <body>
-<script type="text/javascript">
-var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
-document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
-</script>
-<script type="text/javascript">
-try {
-var pageTracker = _gat._getTracker("UA-7597274-3");
-pageTracker._trackPageview();
-} catch(err) {}</script>
-</body>
-</html>
-    
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/dist.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<html>
-    <head>
-        <meta http-equiv="refresh" content=" 1 ; URL=plugin/xdist.html" />
-    </head>
-
-    <body>
-<script type="text/javascript">
-var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
-document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
-</script>
-<script type="text/javascript">
-try {
-var pageTracker = _gat._getTracker("UA-7597274-3");
-pageTracker._trackPageview();
-} catch(err) {}</script>
-</body>
-</html>
-    
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/extend.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<html>
-    <head>
-        <meta http-equiv="refresh" content=" 1 ; URL=customize.html" />
-    </head>
-
-    <body>
-<script type="text/javascript">
-var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
-document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
-</script>
-<script type="text/javascript">
-try {
-var pageTracker = _gat._getTracker("UA-7597274-3");
-pageTracker._trackPageview();
-} catch(err) {}</script>
-</body>
-</html>
-    
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/index.rst
+++ /dev/null
@@ -1,35 +0,0 @@
-=======================================
-pytest documentation index
-=======================================
-
-
-features_: overview and discussion of features.
-
-quickstart_: getting started with writing a simple test.
-
-`talks, tutorials, examples`_: tutorial examples, slides
-
-funcargs_: powerful parametrized test function setup
-
-`plugins`_: list of available plugins with usage examples and feature details.
-
-customize_: configuration, customization, extensions
-
-changelog_: history of changes covering last releases
-
-**Continuous Integration of pytest's own tests and plugins with Hudson**:
-
-    `http://hudson.testrun.org/view/pytest`_
-
-.. _`http://hudson.testrun.org/view/pytest`: http://hudson.testrun.org/view/pytest/
-
-
-.. _changelog: ../changelog.html
-.. _`plugins`: plugin/index.html
-.. _`talks, tutorials, examples`: talks.html
-.. _quickstart: quickstart.html
-.. _features: features.html
-.. _funcargs: funcargs.html
-.. _customize: customize.html
-
-
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/mission.rst
+++ /dev/null
@@ -1,13 +0,0 @@
-
-Mission
-====================================
-
-``pytest`` strives to make testing a fun and no-boilerplate effort.
-
-The tool is distributed as a `pytest` package.  Its project independent
-``pytest`` command line tool helps you to:
-
-* rapidly collect and run tests
-* run unit- or doctests, functional or integration tests
-* distribute tests to multiple environments
-* use local or global plugins for custom test types and setup
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/cov.rst
+++ /dev/null
@@ -1,230 +0,0 @@
-
-produce code coverage reports using the 'coverage' package, including support for distributed testing.
-======================================================================================================
-
-
-.. contents::
-  :local:
-
-This plugin produces coverage reports.  It supports centralised testing and distributed testing in
-both load and each modes.  It also supports coverage of subprocesses.
-
-All features offered by the coverage package should be available, either through pytest-cov or
-through coverage's config file.
-
-
-Installation
-------------
-
-The `pytest-cov`_ package may be installed with pip or easy_install::
-
-    pip install pytest-cov
-    easy_install pytest-cov
-
-.. _`pytest-cov`: http://pypi.python.org/pypi/pytest-cov/
-
-
-Uninstallation
---------------
-
-Uninstalling packages is supported by pip::
-
-    pip uninstall pytest-cov
-
-However easy_install does not provide an uninstall facility.
-
-.. IMPORTANT::
-
-    Ensure that you manually delete the init_covmain.pth file in your
-    site-packages directory.
-
-    This file starts coverage collection of subprocesses if appropriate during
-    site initialization at python startup.
-
-
-Usage
------
-
-Centralised Testing
-~~~~~~~~~~~~~~~~~~~
-
-Centralised testing will report on the combined coverage of the main process and all of it's
-subprocesses.
-
-Running centralised testing::
-
-    pytest --cov myproj tests/
-
-Shows a terminal report::
-
-    -------------------- coverage: platform linux2, python 2.6.4-final-0 ---------------------
-    Name                 Stmts   Miss  Cover
-    ----------------------------------------
-    myproj/__init__          2      0   100%
-    myproj/myproj          257     13    94%
-    myproj/feature4286      94      7    92%
-    ----------------------------------------
-    TOTAL                  353     20    94%
-
-
-Distributed Testing: Load
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Distributed testing with dist mode set to load will report on the combined coverage of all slaves.
-The slaves may be spread out over any number of hosts and each slave may be located anywhere on the
-file system.  Each slave will have it's subprocesses measured.
-
-Running distributed testing with dist mode set to load::
-
-    pytest --cov myproj -n 2 tests/
-
-Shows a terminal report::
-
-    -------------------- coverage: platform linux2, python 2.6.4-final-0 ---------------------
-    Name                 Stmts   Miss  Cover
-    ----------------------------------------
-    myproj/__init__          2      0   100%
-    myproj/myproj          257     13    94%
-    myproj/feature4286      94      7    92%
-    ----------------------------------------
-    TOTAL                  353     20    94%
-
-
-Again but spread over different hosts and different directories::
-
-    pytest --cov myproj --dist load
-            --tx ssh=memedough@host1//chdir=testenv1
-            --tx ssh=memedough@host2//chdir=/tmp/testenv2//python=/tmp/env1/bin/python
-            --rsyncdir myproj --rsyncdir tests --rsync examples
-            tests/
-
-Shows a terminal report::
-
-    -------------------- coverage: platform linux2, python 2.6.4-final-0 ---------------------
-    Name                 Stmts   Miss  Cover
-    ----------------------------------------
-    myproj/__init__          2      0   100%
-    myproj/myproj          257     13    94%
-    myproj/feature4286      94      7    92%
-    ----------------------------------------
-    TOTAL                  353     20    94%
-
-
-Distributed Testing: Each
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Distributed testing with dist mode set to each will report on the combined coverage of all slaves.
-Since each slave is running all tests this allows generating a combined coverage report for multiple
-environments.
-
-Running distributed testing with dist mode set to each::
-
-    pytest --cov myproj --dist each
-            --tx popen//chdir=/tmp/testenv3//python=/usr/local/python27/bin/python
-            --tx ssh=memedough@host2//chdir=/tmp/testenv4//python=/tmp/env2/bin/python
-            --rsyncdir myproj --rsyncdir tests --rsync examples
-            tests/
-
-Shows a terminal report::
-
-    ---------------------------------------- coverage ----------------------------------------
-                              platform linux2, python 2.6.5-final-0
-                              platform linux2, python 2.7.0-final-0
-    Name                 Stmts   Miss  Cover
-    ----------------------------------------
-    myproj/__init__          2      0   100%
-    myproj/myproj          257     13    94%
-    myproj/feature4286      94      7    92%
-    ----------------------------------------
-    TOTAL                  353     20    94%
-
-
-Reporting
----------
-
-It is possible to generate any combination of the reports for a single test run.
-
-The available reports are terminal (with or without missing line numbers shown), HTML, XML and
-annotated source code.
-
-The terminal report without line numbers (default)::
-
-    pytest --cov-report term --cov myproj tests/
-
-    -------------------- coverage: platform linux2, python 2.6.4-final-0 ---------------------
-    Name                 Stmts   Miss  Cover
-    ----------------------------------------
-    myproj/__init__          2      0   100%
-    myproj/myproj          257     13    94%
-    myproj/feature4286      94      7    92%
-    ----------------------------------------
-    TOTAL                  353     20    94%
-
-
-The terminal report with line numbers::
-
-    pytest --cov-report term-missing --cov myproj tests/
-
-    -------------------- coverage: platform linux2, python 2.6.4-final-0 ---------------------
-    Name                 Stmts   Miss  Cover   Missing
-    --------------------------------------------------
-    myproj/__init__          2      0   100%
-    myproj/myproj          257     13    94%   24-26, 99, 149, 233-236, 297-298, 369-370
-    myproj/feature4286      94      7    92%   183-188, 197
-    --------------------------------------------------
-    TOTAL                  353     20    94%
-
-
-The remaining three reports output to files without showing anything on the terminal (useful for
-when the output is going to a continuous integration server)::
-
-    pytest --cov-report html --cov-report xml --cov-report annotate --cov myproj tests/
-
-
-Coverage Data File
-------------------
-
-The data file is erased at the beginning of testing to ensure clean data for each test run.
-
-The data file is left at the end of testing so that it is possible to use normal coverage tools to
-examine it.
-
-
-Limitations
------------
-
-For distributed testing the slaves must have the pytest-cov package installed.  This is needed since
-the plugin must be registered through setuptools / distribute for pytest to start the plugin on the
-slave.
-
-For subprocess measurement environment variables must make it from the main process to the
-subprocess.  The python used by the subprocess must have pytest-cov installed.  The subprocess must
-do normal site initialization so that the environment variables can be detected and coverage
-started.
-
-
-Acknowledgments
-----------------
-
-Holger Krekel for pytest with its distributed testing support.
-
-Ned Batchelder for coverage and its ability to combine the coverage results of parallel runs.
-
-Whilst this plugin has been built fresh from the ground up to support distributed testing it has
-been influenced by the work done on pytest-coverage (Ross Lawley, James Mills, Holger Krekel) and
-nose-cover (Jason Pellerin) which are other coverage plugins for pytest and nose respectively.
-
-No doubt others have contributed to these tools as well.
-
-command line options
---------------------
-
-
-``--cov=path``
-    measure coverage for filesystem path (multi-allowed)
-``--cov-report=type``
-    type of report to generate: term, term-missing, annotate, html, xml (multi-allowed)
-``--cov-config=path``
-    config file for coverage, default: .coveragerc
-
-.. include:: links.txt
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/coverage.rst
+++ /dev/null
@@ -1,51 +0,0 @@
-
-Write and report coverage data with the 'coverage' package.
-===========================================================
-
-
-.. contents::
-  :local:
-
-Note: Original code by Ross Lawley. 
-
-Install
---------------
-
-Use pip to (un)install::
-
-    pip install pytest-coverage 
-    pip uninstall pytest-coverage 
-
-or alternatively use easy_install to install::
-
-    easy_install pytest-coverage 
-
-
-Usage 
--------------
-
-To get full test coverage reports for a particular package type::
-
-    pytest --cover-report=report
-
-command line options
---------------------
-
-
-``--cover=COVERPACKAGES``
-    (multi allowed) only include info from specified package.
-``--cover-report=REPORT_TYPE``
-    html: Directory for html output.
-                    report: Output a text report.
-                    annotate: Annotate your source code for which lines were executed and which were not.
-                    xml: Output an xml report compatible with the cobertura plugin for hudson.
-``--cover-directory=DIRECTORY``
-    Directory for the reports (html / annotate results) defaults to ./coverage
-``--cover-xml-file=XML_FILE``
-    File for the xml report defaults to ./coverage.xml
-``--cover-show-missing``
-    Show missing files
-``--cover-ignore-errors=IGNORE_ERRORS``
-    Ignore errors of finding source files for code.
-
-.. include:: links.txt
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/django.rst
+++ /dev/null
@@ -1,7 +0,0 @@
-pytest_django plugin (EXTERNAL)
-==========================================
-
-pytest_django is a plugin for ``pytest`` that provides a set of useful tools for testing Django applications, checkout Ben Firshman's `pytest_django github page`_.
-
-.. _`pytest_django github page`: http://github.com/bfirsh/pytest_django/tree/master
-
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/figleaf.rst
+++ /dev/null
@@ -1,44 +0,0 @@
-
-report test coverage using the 'figleaf' package.
-=================================================
-
-
-.. contents::
-  :local:
-
-Install
----------------
-
-To install the plugin issue::
-
-    easy_install pytest-figleaf  # or
-    pip install pytest-figleaf   
-
-and if you are using pip you can also uninstall::
-
-    pip uninstall pytest-figleaf
-
-
-Usage
----------------
-
-After installation you can simply type::
-
-    pytest --figleaf [...]
-
-to enable figleaf coverage in your test run.  A default ".figleaf" data file
-and "html" directory will be created.  You can use command line options
-to control where data and html files are created.
-
-command line options
---------------------
-
-
-``--figleaf``
-    trace python coverage with figleaf and write HTML for files below the current working dir
-``--fig-data=dir``
-    set tracing file, default: ".figleaf".
-``--fig-html=dir``
-    set html reporting dir, default "html".
-
-.. include:: links.txt
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/helpconfig.rst
+++ /dev/null
@@ -1,36 +0,0 @@
-
-provide version info, conftest/environment config names.
-========================================================
-
-
-.. contents::
-  :local:
-
-
-
-command line options
---------------------
-
-
-``--version``
-    display py lib version and import information.
-``-p name``
-    early-load given plugin (multi-allowed).
-``--trace-config``
-    trace considerations of conftest.py files.
-``--debug``
-    generate and show internal debugging information.
-``--help-config``
-    show available conftest.py and ENV-variable names.
-
-Start improving this plugin in 30 seconds
-=========================================
-
-
-1. Download `pytest_helpconfig.py`_ plugin source code
-2. put it somewhere as ``pytest_helpconfig.py`` into your import path
-3. a subsequent ``pytest`` run will use your local version
-
-Checkout customize_, other plugins_ or `get in contact`_.
-
-.. include:: links.txt
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/index.rst
+++ /dev/null
@@ -1,68 +0,0 @@
-
-advanced python testing
-=======================
-
-skipping_ advanced skipping for python test functions, classes or modules.
-
-mark_ generic mechanism for marking python functions.
-
-pdb_ interactive debugging with the Python Debugger.
-
-figleaf_ (external) report test coverage using the 'figleaf' package.
-
-monkeypatch_ safely patch object attributes, dicts and environment variables.
-
-coverage_ (external) Write and report coverage data with the 'coverage' package.
-
-cov_ (external) produce code coverage reports using the 'coverage' package, including support for distributed testing.
-
-capture_ configurable per-test stdout/stderr capturing mechanisms.
-
-capturelog_ (external) capture output of logging module.
-
-recwarn_ helpers for asserting deprecation and other warnings.
-
-tmpdir_ provide temporary directories to test functions.
-
-
-distributed testing, CI and deployment
-======================================
-
-xdist_ (external) loop on failing tests, distribute test runs to CPUs and hosts.
-
-pastebin_ submit failure or test session information to a pastebin service.
-
-junitxml_ logging of test results in JUnit-XML format, for use with Hudson
-
-resultlog_ non-xml machine-readable logging of test results.
-
-genscript_ generate standalone test script to be distributed along with an application.
-
-
-testing domains and conventions codecheckers
-============================================
-
-oejskit_ (external) run javascript tests in real life browsers
-
-django_ (external) for testing django applications
-
-unittest_ automatically discover and run traditional "unittest.py" style tests.
-
-nose_ nose-compatibility plugin: allow to run nose test suites natively.
-
-doctest_ collect and execute doctests from modules and test files.
-
-restdoc_ perform ReST syntax, local and remote reference tests on .rst/.txt files.
-
-
-internal, debugging, help functionality
-=======================================
-
-helpconfig_ provide version info, conftest/environment config names.
-
-terminal_ Implements terminal reporting of the full testing process.
-
-hooklog_ log invocations of extension hooks to a file.
-
-
-.. include:: links.txt
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/links.rst
+++ /dev/null
@@ -1,45 +0,0 @@
-.. _`helpconfig`: helpconfig.html
-.. _`pytest_recwarn.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_recwarn.py
-.. _`unittest`: unittest.html
-.. _`pytest_monkeypatch.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_monkeypatch.py
-.. _`pastebin`: pastebin.html
-.. _`skipping`: skipping.html
-.. _`plugins`: index.html
-.. _`mark`: mark.html
-.. _`tmpdir`: tmpdir.html
-.. _`pytest_doctest.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_doctest.py
-.. _`capture`: capture.html
-.. _`pytest_nose.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_nose.py
-.. _`pytest_restdoc.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_restdoc.py
-.. _`restdoc`: restdoc.html
-.. _`xdist`: xdist.html
-.. _`pytest_pastebin.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_pastebin.py
-.. _`pytest_tmpdir.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_tmpdir.py
-.. _`terminal`: terminal.html
-.. _`pytest_hooklog.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_hooklog.py
-.. _`capturelog`: capturelog.html
-.. _`junitxml`: junitxml.html
-.. _`pytest_skipping.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_skipping.py
-.. _`checkout the pytest development version`: ../../install.html#checkout
-.. _`pytest_helpconfig.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_helpconfig.py
-.. _`oejskit`: oejskit.html
-.. _`doctest`: doctest.html
-.. _`pytest_mark.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_mark.py
-.. _`get in contact`: ../../contact.html
-.. _`pytest_capture.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_capture.py
-.. _`figleaf`: figleaf.html
-.. _`customize`: ../customize.html
-.. _`hooklog`: hooklog.html
-.. _`pytest_terminal.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_terminal.py
-.. _`recwarn`: recwarn.html
-.. _`pytest_pdb.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_pdb.py
-.. _`monkeypatch`: monkeypatch.html
-.. _`coverage`: coverage.html
-.. _`resultlog`: resultlog.html
-.. _`cov`: cov.html
-.. _`pytest_junitxml.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_junitxml.py
-.. _`django`: django.html
-.. _`pytest_unittest.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_unittest.py
-.. _`nose`: nose.html
-.. _`pytest_resultlog.py`: http://bitbucket.org/hpk42/py-trunk/raw/1.3.4/py/_plugin/pytest_resultlog.py
-.. _`pdb`: pdb.html
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/nose.rst
+++ /dev/null
@@ -1,56 +0,0 @@
-
-nose-compatibility plugin: allow to run nose test suites natively.
-==================================================================
-
-
-.. contents::
-  :local:
-
-This is an experimental plugin for allowing to run tests written
-in 'nosetests' style with ``pytest``.
-
-Usage
--------------
-
-type::
-
-    pytest  # instead of 'nosetests'
-
-and you should be able to run nose style tests and at the same
-time can make full use of pytest's capabilities.
-
-Supported nose Idioms
-----------------------
-
-* setup and teardown at module/class/method level
-* SkipTest exceptions and markers
-* setup/teardown decorators
-* yield-based tests and their setup
-* general usage of nose utilities
-
-Unsupported idioms / issues
-----------------------------------
-
-- nose-style doctests are not collected and executed correctly,
-  also fixtures don't work.
-
-- no nose-configuration is recognized
-
-If you find other issues or have suggestions please run::
-
-    pytest --pastebin=all
-
-and send the resulting URL to a ``pytest`` contact channel,
-at best to the mailing list.
-
-Start improving this plugin in 30 seconds
-=========================================
-
-
-1. Download `pytest_nose.py`_ plugin source code
-2. put it somewhere as ``pytest_nose.py`` into your import path
-3. a subsequent ``pytest`` run will use your local version
-
-Checkout customize_, other plugins_ or `get in contact`_.
-
-.. include:: links.txt
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/oejskit.rst
+++ /dev/null
@@ -1,12 +0,0 @@
-pytest_oejskit plugin (EXTERNAL)
-==========================================
-
-The `oejskit`_ offers a ``pytest`` plugin for running Javascript tests in live browsers.   Running inside the browsers comes with some speed cost, on the other hand it means for example the code is tested against the real-word DOM implementations.
-The approach enables to write integration tests such that the JavaScript code is tested against server-side Python code mocked as necessary. Any server-side framework that can already be exposed through WSGI (or for which a subset of WSGI can be written to accommodate the jskit own needs) can play along.
-
-For more info and download please visit the `oejskit PyPI`_ page.
-
-.. _`oejskit`:
-.. _`oejskit PyPI`: http://pypi.python.org/pypi/oejskit
-
-.. source link 'http://bitbucket.org/pedronis/js-infrastructure/src/tip/pytest_jstests.py',
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/terminal.rst
+++ /dev/null
@@ -1,38 +0,0 @@
-
-Implements terminal reporting of the full testing process.
-==========================================================
-
-
-.. contents::
-  :local:
-
-This is a good source for looking at the various reporting hooks.
-
-command line options
---------------------
-
-
-``-v, --verbose``
-    increase verbosity.
-``-r chars``
-    show extra test summary info as specified by chars (f)ailed, (s)skipped, (x)failed, (X)passed.
-``-l, --showlocals``
-    show locals in tracebacks (disabled by default).
-``--tb=style``
-    traceback print mode (long/short/line/no).
-``--full-trace``
-    don't cut any tracebacks (default is to cut).
-``--fixtures``
-    show available function arguments, sorted by plugin
-
-Start improving this plugin in 30 seconds
-=========================================
-
-
-1. Download `pytest_terminal.py`_ plugin source code
-2. put it somewhere as ``pytest_terminal.py`` into your import path
-3. a subsequent ``pytest`` run will use your local version
-
-Checkout customize_, other plugins_ or `get in contact`_.
-
-.. include:: links.txt
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/plugin/xdist.rst
+++ /dev/null
@@ -1,172 +0,0 @@
-
-loop on failing tests, distribute test runs to CPUs and hosts.
-==============================================================
-
-
-.. contents::
-  :local:
-
-The `pytest-xdist`_ plugin extends ``pytest`` with some unique
-test execution modes:
-
-* Looponfail: run your tests repeatedly in a subprocess.  After each run
-  ``pytest`` waits until a file in your project changes and then re-runs the
-  previously failing tests.  This is repeated until all tests pass after which
-  again a full run is performed.
-
-* Load-balancing: if you have multiple CPUs or hosts you can use
-  those for a combined test run.  This allows to speed up
-  development or to use special resources of remote machines.
-
-* Multi-Platform coverage: you can specify different Python interpreters
-  or different platforms and run tests in parallel on all of them.
-
-Before running tests remotely, ``pytest`` efficiently synchronizes your
-program source code to the remote place.  All test results
-are reported back and displayed to your local test session.
-You may specify different Python versions and interpreters.
-
-.. _`pytest-xdist`: http://pypi.python.org/pypi/pytest-xdist
-
-Usage examples
----------------------
-
-Speed up test runs by sending tests to multiple CPUs
-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-
-To send tests to multiple CPUs, type::
-
-    pytest -n NUM
-
-Especially for longer running tests or tests requiring
-a lot of IO this can lead to considerable speed ups.
-
-
-Running tests in a Python subprocess
-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-
-To instantiate a python2.4 sub process and send tests to it, you may type::
-
-    pytest -d --tx popen//python=python2.4
-
-This will start a subprocess which is run with the "python2.4"
-Python interpreter, found in your system binary lookup path.
-
-If you prefix the --tx option value like this::
-
-    --tx 3*popen//python=python2.4
-
-then three subprocesses would be created and tests
-will be load-balanced across these three processes.
-
-
-Sending tests to remote SSH accounts
-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-
-Suppose you have a package ``mypkg`` which contains some
-tests that you can successfully run locally. And you
-have a ssh-reachable machine ``myhost``.  Then
-you can ad-hoc distribute your tests by typing::
-
-    pytest -d --tx ssh=myhostpopen --rsyncdir mypkg mypkg
-
-This will synchronize your ``mypkg`` package directory
-to a remote ssh account and then locally collect tests
-and send them to remote places for execution.
-
-You can specify multiple ``--rsyncdir`` directories
-to be sent to the remote side.
-
-**NOTE:** For ``pytest`` to collect and send tests correctly
-you not only need to make sure all code and tests
-directories are rsynced, but that any test (sub) directory
-also has an ``__init__.py`` file because internally
-``pytest`` references tests using their fully qualified python
-module path.  **You will otherwise get strange errors**
-during setup of the remote side.
-
-Sending tests to remote Socket Servers
-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-
-Download the single-module `socketserver.py`_ Python program
-and run it like this::
-
-    python socketserver.py
-
-It will tell you that it starts listening on the default
-port.  You can now on your home machine specify this
-new socket host with something like this::
-
-    pytest -d --tx socket=192.168.1.102:8888 --rsyncdir mypkg mypkg
-
-
-.. _`atonce`:
-
-Running tests on many platforms at once
-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-
-The basic command to run tests on multiple platforms is::
-
-    pytest --dist=each --tx=spec1 --tx=spec2
-
-If you specify a windows host, an OSX host and a Linux
-environment this command will send each tests to all
-platforms - and report back failures from all platforms
-at once.   The specifications strings use the `xspec syntax`_.
-
-.. _`xspec syntax`: http://codespeak.net/execnet/trunk/basics.html#xspec
-
-.. _`socketserver.py`: http://codespeak.net/svn/py/dist/py/execnet/script/socketserver.py
-
-.. _`execnet`: http://codespeak.net/execnet
-
-Specifying test exec environments in a conftest.py
-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-
-Instead of specifying command line options, you can
-put options values in a ``conftest.py`` file like this::
-
-    option_tx = ['ssh=myhost//python=python2.7', 'popen//python=python2.7']
-    option_dist = True
-
-Any commandline ``--tx`` specifications  will add to the list of
-available execution environments.
-
-Specifying "rsync" dirs in a conftest.py
-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-
-In your ``mypkg/conftest.py`` you may specify directories to synchronise
-or to exclude::
-
-    rsyncdirs = ['.', '../plugins']
-    rsyncignore = ['_cache']
-
-These directory specifications are relative to the directory
-where the ``conftest.py`` is found.
-
-command line options
---------------------
-
-
-``-f, --looponfail``
-    run tests in subprocess, wait for modified files and re-run failing test set until all pass.
-``-n numprocesses``
-    shortcut for '--dist=load --tx=NUM*popen'
-``--boxed``
-    box each test run in a separate process (unix)
-``--dist=distmode``
-    set mode for distributing tests to exec environments.
-
-    each: send each test to each available environment.
-
-    load: send each test to one available environment so it is run only once.
-
-    (default) no: run tests inprocess, don't distribute.
-``--tx=xspec``
-    add a test execution environment. some examples: --tx popen//python=python2.7 --tx socket=192.168.1.102:8888 --tx ssh=user@codespeak.net//chdir=testcache
-``-d``
-    load-balance tests.  shortcut for '--dist=load'
-``--rsyncdir=dir1``
-    add directory for rsyncing to remote tx nodes.
-
-.. include:: links.txt
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/test/test.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<html>
-    <head>
-        <meta http-equiv="refresh" content=" 1 ; URL=index.html" />
-    </head>
-
-    <body>
-<script type="text/javascript">
-var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
-document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
-</script>
-<script type="text/javascript">
-try {
-var pageTracker = _gat._getTracker("UA-7597274-3");
-pageTracker._trackPageview();
-} catch(err) {}</script>
-</body>
-</html>
-    
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/tmpdir.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/tmpdir.rst
@@ -27,35 +27,37 @@ and more.  Here is an example test usage
 Running this would result in a passed test except for the last
 ``assert 0`` line which we use to look at values::
 
     $ pytest test_tmpdir.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 1 item
-    
+
     test_tmpdir.py F                                                     [100%]
-    
+
     ================================= FAILURES =================================
     _____________________________ test_create_file _____________________________
-    
+
     tmpdir = local('PYTEST_TMPDIR/test_create_file0')
-    
+
         def test_create_file(tmpdir):
             p = tmpdir.mkdir("sub").join("hello.txt")
             p.write("content")
             assert p.read() == "content"
             assert len(tmpdir.listdir()) == 1
     >       assert 0
     E       assert 0
-    
+
     test_tmpdir.py:7: AssertionError
     ========================= 1 failed in 0.12 seconds =========================
 
+.. _`tmpdir factory example`:
+
 The 'tmpdir_factory' fixture
 ----------------------------
 
 .. versionadded:: 2.8
 
 The ``tmpdir_factory`` is a session-scoped fixture which can be used
 to create arbitrary temporary directories from any other fixture or test.
 
@@ -64,34 +66,32 @@ generated procedurally. Instead of compu
 that uses it into its own ``tmpdir``, you can generate it once per-session
 to save time:
 
 .. code-block:: python
 
     # contents of conftest.py
     import pytest
 
-    @pytest.fixture(scope='session')
+
+    @pytest.fixture(scope="session")
     def image_file(tmpdir_factory):
         img = compute_expensive_image()
-        fn = tmpdir_factory.mktemp('data').join('img.png')
+        fn = tmpdir_factory.mktemp("data").join("img.png")
         img.save(str(fn))
         return fn
 
+
     # contents of test_image.py
     def test_histogram(image_file):
         img = load_image(image_file)
         # compute and test histogram
 
-``tmpdir_factory`` instances have the following methods:
+See :ref:`tmpdir_factory API <tmpdir factory api>` for details.
 
-.. currentmodule:: _pytest.tmpdir
-
-.. automethod:: TempdirFactory.mktemp
-.. automethod:: TempdirFactory.getbasetemp
 
 .. _`base temporary directory`:
 
 The default base temporary directory
 -----------------------------------------------
 
 Temporary directories are by default created as sub-directories of
 the system temporary directory.  The base name will be ``pytest-NUM`` where
@@ -101,11 +101,9 @@ than 3 temporary directories will be rem
 You can override the default temporary directory setting like this::
 
     pytest --basetemp=mydir
 
 When distributing tests on the local machine, ``pytest`` takes care to
 configure a basetemp directory for the sub processes such that all temporary
 data lands below a single per-test run basetemp directory.
 
-.. _`py.path.local`: http://py.rtfd.org/en/latest/path.html
-
-
+.. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/unittest.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/unittest.rst
@@ -41,19 +41,19 @@ By running your test suite with pytest y
 in most cases without having to modify existing code:
 
 * Obtain :ref:`more informative tracebacks <tbreportdemo>`;
 * :ref:`stdout and stderr <captures>` capturing;
 * :ref:`Test selection options <select-tests>` using ``-k`` and ``-m`` flags;
 * :ref:`maxfail`;
 * :ref:`--pdb <pdb-option>` command-line option for debugging on test failures
   (see :ref:`note <pdb-unittest-note>` below);
-* Distribute tests to multiple CPUs using the `pytest-xdist <http://pypi.python.org/pypi/pytest-xdist>`_ plugin;
+* Distribute tests to multiple CPUs using the `pytest-xdist <https://pypi.org/project/pytest-xdist/>`_ plugin;
 * Use :ref:`plain assert-statements <assert>` instead of ``self.assert*`` functions (`unittest2pytest
-  <https://pypi.python.org/pypi/unittest2pytest/>`__ is immensely helpful in this);
+  <https://pypi.org/project/unittest2pytest/>`__ is immensely helpful in this);
 
 
 pytest features in ``unittest.TestCase`` subclasses
 ---------------------------------------------------
 
 The following pytest features work in ``unittest.TestCase`` subclasses:
 
 * :ref:`Marks <mark>`: :ref:`skip <skip>`, :ref:`skipif <skipif>`, :ref:`xfail <xfail>`;
@@ -87,94 +87,94 @@ it from a unittest-style test::
     # referencing its name from tests
 
     import pytest
 
     @pytest.fixture(scope="class")
     def db_class(request):
         class DummyDB(object):
             pass
-        # set a class attribute on the invoking test context 
+        # set a class attribute on the invoking test context
         request.cls.db = DummyDB()
 
-This defines a fixture function ``db_class`` which - if used - is 
-called once for each test class and which sets the class-level 
+This defines a fixture function ``db_class`` which - if used - is
+called once for each test class and which sets the class-level
 ``db`` attribute to a ``DummyDB`` instance.  The fixture function
 achieves this by receiving a special ``request`` object which gives
 access to :ref:`the requesting test context <request-context>` such
-as the ``cls`` attribute, denoting the class from which the fixture 
+as the ``cls`` attribute, denoting the class from which the fixture
 is used.  This architecture de-couples fixture writing from actual test
 code and allows re-use of the fixture by a minimal reference, the fixture
-name.  So let's write an actual ``unittest.TestCase`` class using our 
+name.  So let's write an actual ``unittest.TestCase`` class using our
 fixture definition::
 
     # content of test_unittest_db.py
 
     import unittest
     import pytest
 
     @pytest.mark.usefixtures("db_class")
     class MyTest(unittest.TestCase):
         def test_method1(self):
             assert hasattr(self, "db")
             assert 0, self.db   # fail for demo purposes
 
         def test_method2(self):
             assert 0, self.db   # fail for demo purposes
 
-The ``@pytest.mark.usefixtures("db_class")`` class-decorator makes sure that 
+The ``@pytest.mark.usefixtures("db_class")`` class-decorator makes sure that
 the pytest fixture function ``db_class`` is called once per class.
 Due to the deliberately failing assert statements, we can take a look at
 the ``self.db`` values in the traceback::
 
     $ pytest test_unittest_db.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 2 items
-    
+
     test_unittest_db.py FF                                               [100%]
-    
+
     ================================= FAILURES =================================
     ___________________________ MyTest.test_method1 ____________________________
-    
+
     self = <test_unittest_db.MyTest testMethod=test_method1>
-    
+
         def test_method1(self):
             assert hasattr(self, "db")
     >       assert 0, self.db   # fail for demo purposes
     E       AssertionError: <conftest.db_class.<locals>.DummyDB object at 0xdeadbeef>
     E       assert 0
-    
+
     test_unittest_db.py:9: AssertionError
     ___________________________ MyTest.test_method2 ____________________________
-    
+
     self = <test_unittest_db.MyTest testMethod=test_method2>
-    
+
         def test_method2(self):
     >       assert 0, self.db   # fail for demo purposes
     E       AssertionError: <conftest.db_class.<locals>.DummyDB object at 0xdeadbeef>
     E       assert 0
-    
+
     test_unittest_db.py:12: AssertionError
     ========================= 2 failed in 0.12 seconds =========================
 
 This default pytest traceback shows that the two test methods
 share the same ``self.db`` instance which was our intention
 when writing the class-scoped fixture function above.
 
 
 Using autouse fixtures and accessing other fixtures
 ---------------------------------------------------
 
 Although it's usually better to explicitly declare use of fixtures you need
-for a given test, you may sometimes want to have fixtures that are 
-automatically used in a given context.  After all, the traditional 
+for a given test, you may sometimes want to have fixtures that are
+automatically used in a given context.  After all, the traditional
 style of unittest-setup mandates the use of this implicit fixture writing
-and chances are, you are used to it or like it.  
+and chances are, you are used to it or like it.
 
 You can flag fixture functions with ``@pytest.fixture(autouse=True)``
 and define the fixture function in the context where you want it used.
 Let's look at an ``initdir`` fixture which makes all test methods of a
 ``TestCase`` class execute in a temporary directory with a
 pre-initialized ``samplefile.ini``.  Our ``initdir`` fixture itself uses
 the pytest builtin :ref:`tmpdir <tmpdir>` fixture to delegate the
 creation of a per-test temporary directory::
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/usage.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/usage.rst
@@ -106,19 +106,19 @@ Will run all tests which are decorated w
 
 For more information see :ref:`marks <mark>`.
 
 **Run tests from packages**
 
 ::
 
     pytest --pyargs pkg.testing
-     
+
 This will import ``pkg.testing`` and use its filesystem location to find and run tests from.
-    
+
 
 Modifying Python traceback printing
 ----------------------------------------------
 
 Examples for modifying traceback printing::
 
     pytest --showlocals # show local variables in tracebacks
     pytest -l           # show local variables (shortcut)
@@ -147,19 +147,19 @@ Dropping to PDB_ (Python Debugger) on fa
 
 .. _PDB: http://docs.python.org/library/pdb.html
 
 Python comes with a builtin Python debugger called PDB_.  ``pytest``
 allows one to drop into the PDB_ prompt via a command line option::
 
     pytest --pdb
 
-This will invoke the Python debugger on every failure.  Often you might
-only want to do this for the first failing test to understand a certain
-failure situation::
+This will invoke the Python debugger on every failure (or KeyboardInterrupt).
+Often you might only want to do this for the first failing test to understand
+a certain failure situation::
 
     pytest -x --pdb   # drop to PDB on first failure, then end test session
     pytest --pdb --maxfail=3  # drop to PDB for first three failures
 
 Note that on any failure the exception information is stored on
 ``sys.last_value``, ``sys.last_type`` and ``sys.last_traceback``. In
 interactive use, this allows one to drop into postmortem debugging with
 any debug tool. One can also manually access the exception information,
@@ -184,16 +184,30 @@ in your code and pytest automatically di
 * Output capture in other tests is not affected.
 * Any prior test output that has already been captured and will be processed as
   such.
 * Any later output produced within the same test will not be captured and will
   instead get sent directly to ``sys.stdout``. Note that this holds true even
   for test output occurring after you exit the interactive PDB_ tracing session
   and continue with the regular test run.
 
+
+.. _`breakpoint-builtin`:
+
+Using the builtin breakpoint function
+-------------------------------------
+
+Python 3.7 introduces a builtin ``breakpoint()`` function.
+Pytest supports the use of ``breakpoint()`` with the following behaviours:
+
+ - When ``breakpoint()`` is called and ``PYTHONBREAKPOINT`` is set to the default value, pytest will use the custom internal PDB trace UI instead of the system default ``Pdb``.
+ - When tests are complete, the system will default back to the system ``Pdb`` trace UI.
+ - If ``--pdb`` is called on execution of pytest, the custom internal Pdb trace UI is used on ``bothbreakpoint()`` and failed tests/unhandled exceptions.
+ - If ``--pdbcls`` is used, the custom class debugger will be executed when a test fails (as expected within existing behaviour), but also when ``breakpoint()`` is called from within a test, the custom class debugger will be instantiated.
+
 .. _durations:
 
 Profiling test execution duration
 -------------------------------------
 
 .. versionadded: 2.2
 
 To get a list of the slowest 10 test durations::
@@ -215,77 +229,178 @@ to create an XML file at ``path``.
 
 To set the name of the root test suite xml item, you can configure the ``junit_suite_name`` option in your config file:
 
 .. code-block:: ini
 
     [pytest]
     junit_suite_name = my_suite
 
-record_xml_property
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+.. _record_property example:
+
+record_property
+^^^^^^^^^^^^^^^
 
 .. versionadded:: 2.8
+.. versionchanged:: 3.5
+
+   Fixture renamed from ``record_xml_property`` to ``record_property`` as user
+   properties are now available to all reporters.
+   ``record_xml_property`` is now deprecated.
 
 If you want to log additional information for a test, you can use the
-``record_xml_property`` fixture:
+``record_property`` fixture:
 
 .. code-block:: python
 
-    def test_function(record_xml_property):
-        record_xml_property("example_key", 1)
-        assert 0
+    def test_function(record_property):
+        record_property("example_key", 1)
+        assert True
 
 This will add an extra property ``example_key="1"`` to the generated
 ``testcase`` tag:
 
 .. code-block:: xml
 
     <testcase classname="test_function" file="test_function.py" line="0" name="test_function" time="0.0009">
       <properties>
         <property name="example_key" value="1" />
       </properties>
     </testcase>
 
+Alternatively, you can integrate this functionality with custom markers:
+
+.. code-block:: python
+
+    # content of conftest.py
+
+
+    def pytest_collection_modifyitems(session, config, items):
+        for item in items:
+            for marker in item.iter_markers(name="test_id"):
+                test_id = marker.args[0]
+                item.user_properties.append(("test_id", test_id))
+
+And in your tests:
+
+.. code-block:: python
+
+    # content of test_function.py
+    import pytest
+
+
+    @pytest.mark.test_id(1501)
+    def test_function():
+        assert True
+
+Will result in:
+
+.. code-block:: xml
+
+    <testcase classname="test_function" file="test_function.py" line="0" name="test_function" time="0.0009">
+      <properties>
+        <property name="test_id" value="1501" />
+      </properties>
+    </testcase>
+
 .. warning::
 
-    ``record_xml_property`` is an experimental feature, and its interface might be replaced
+    ``record_property`` is an experimental feature and may change in the future.
+
+    Also please note that using this feature will break any schema verification.
+    This might be a problem when used with some CI servers.
+
+record_xml_attribute
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. versionadded:: 3.4
+
+To add an additional xml attribute to a testcase element, you can use
+``record_xml_attribute`` fixture. This can also be used to override existing values:
+
+.. code-block:: python
+
+    def test_function(record_xml_attribute):
+        record_xml_attribute("assertions", "REQ-1234")
+        record_xml_attribute("classname", "custom_classname")
+        print("hello world")
+        assert True
+
+Unlike ``record_property``, this will not add a new child element.
+Instead, this will add an attribute ``assertions="REQ-1234"`` inside the generated
+``testcase`` tag and override the default ``classname`` with ``"classname=custom_classname"``:
+
+.. code-block:: xml
+
+    <testcase classname="custom_classname" file="test_function.py" line="0" name="test_function" time="0.003" assertions="REQ-1234">
+        <system-out>
+            hello world
+        </system-out>
+    </testcase>
+
+.. warning::
+
+    ``record_xml_attribute`` is an experimental feature, and its interface might be replaced
     by something more powerful and general in future versions. The
     functionality per-se will be kept, however.
 
-    Currently it does not work when used with the ``pytest-xdist`` plugin.
+    Using this over ``record_xml_property`` can help when using ci tools to parse the xml report.
+    However, some parsers are quite strict about the elements and attributes that are allowed.
+    Many tools use an xsd schema (like the example below) to validate incoming xml.
+    Make sure you are using attribute names that are allowed by your parser.
+
+    Below is the Scheme used by Jenkins to validate the XML report:
+
+    .. code-block:: xml
 
-    Also please note that using this feature will break any schema verification.
-    This might be a problem when used with some CI servers.
+        <xs:element name="testcase">
+            <xs:complexType>
+                <xs:sequence>
+                    <xs:element ref="skipped" minOccurs="0" maxOccurs="1"/>
+                    <xs:element ref="error" minOccurs="0" maxOccurs="unbounded"/>
+                    <xs:element ref="failure" minOccurs="0" maxOccurs="unbounded"/>
+                    <xs:element ref="system-out" minOccurs="0" maxOccurs="unbounded"/>
+                    <xs:element ref="system-err" minOccurs="0" maxOccurs="unbounded"/>
+                </xs:sequence>
+                <xs:attribute name="name" type="xs:string" use="required"/>
+                <xs:attribute name="assertions" type="xs:string" use="optional"/>
+                <xs:attribute name="time" type="xs:string" use="optional"/>
+                <xs:attribute name="classname" type="xs:string" use="optional"/>
+                <xs:attribute name="status" type="xs:string" use="optional"/>
+            </xs:complexType>
+        </xs:element>
 
 LogXML: add_global_property
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 .. versionadded:: 3.0
 
 If you want to add a properties node in the testsuite level, which may contains properties that are relevant
 to all testcases you can use ``LogXML.add_global_properties``
 
 .. code-block:: python
 
     import pytest
 
+
     @pytest.fixture(scope="session")
     def log_global_env_facts(f):
 
-        if pytest.config.pluginmanager.hasplugin('junitxml'):
-            my_junit = getattr(pytest.config, '_xml', None)
+        if pytest.config.pluginmanager.hasplugin("junitxml"):
+            my_junit = getattr(pytest.config, "_xml", None)
 
-        my_junit.add_global_property('ARCH', 'PPC')
-        my_junit.add_global_property('STORAGE_TYPE', 'CEPH')
+        my_junit.add_global_property("ARCH", "PPC")
+        my_junit.add_global_property("STORAGE_TYPE", "CEPH")
 
-    @pytest.mark.usefixtures(log_global_env_facts)
+
+    @pytest.mark.usefixtures(log_global_env_facts.__name__)
     def start_and_prepare_env():
         pass
 
+
     class TestMe(object):
         def test_foo(self):
             assert True
 
 This will add a property node below the testsuite node to the generated xml:
 
 .. code-block:: xml
 
@@ -306,17 +421,17 @@ This will add a property node below the 
 Creating resultlog format files
 ----------------------------------------------------
 
 .. deprecated:: 3.0
 
     This option is rarely used and is scheduled for removal in 4.0.
 
     An alternative for users which still need similar functionality is to use the
-    `pytest-tap <https://pypi.python.org/pypi/pytest-tap>`_ plugin which provides
+    `pytest-tap <https://pypi.org/project/pytest-tap/>`_ plugin which provides
     a stream of test data.
 
     If you have any concerns, please don't hesitate to
     `open an issue <https://github.com/pytest-dev/pytest/issues>`_.
 
 To create plain-text machine-readable result files you can issue::
 
     pytest --resultlog=path
@@ -381,12 +496,22 @@ You can specify additional plugins to ``
             print("*** test run reporting finishing")
 
     pytest.main(["-qq"], plugins=[MyPlugin()])
 
 Running it will show that ``MyPlugin`` was added and its
 hook was invoked::
 
     $ python myinvoke.py
-    *** test run reporting finishing
-    
+    .                                                                    [100%]*** test run reporting finishing
+
+
+.. note::
+
+    Calling ``pytest.main()`` will result in importing your tests and any modules
+    that they import. Due to the caching mechanism of python's import system,
+    making subsequent calls to ``pytest.main()`` from the same process will not
+    reflect changes to those files between the calls. For this reason, making
+    multiple calls to ``pytest.main()`` from the same process (in order to re-run
+    tests, for example) is not recommended.
+
 
 .. include:: links.inc
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/warnings.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/warnings.rst
@@ -20,47 +20,47 @@ and displays them at the end of the sess
 
 Running pytest now produces this output::
 
     $ pytest test_show_warnings.py
     =========================== test session starts ============================
     platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
     rootdir: $REGENDOC_TMPDIR, inifile:
     collected 1 item
-    
+
     test_show_warnings.py .                                              [100%]
-    
+
     ============================= warnings summary =============================
     test_show_warnings.py::test_one
       $REGENDOC_TMPDIR/test_show_warnings.py:4: UserWarning: api v1, should use functions from v2
         warnings.warn(UserWarning("api v1, should use functions from v2"))
-    
+
     -- Docs: http://doc.pytest.org/en/latest/warnings.html
     =================== 1 passed, 1 warnings in 0.12 seconds ===================
 
 Pytest by default catches all warnings except for ``DeprecationWarning`` and ``PendingDeprecationWarning``.
 
 The ``-W`` flag can be passed to control which warnings will be displayed or even turn
 them into errors::
 
     $ pytest -q test_show_warnings.py -W error::UserWarning
     F                                                                    [100%]
     ================================= FAILURES =================================
     _________________________________ test_one _________________________________
-    
+
         def test_one():
     >       assert api_v1() == 1
-    
-    test_show_warnings.py:8: 
-    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
-    
+
+    test_show_warnings.py:8:
+    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
+
         def api_v1():
     >       warnings.warn(UserWarning("api v1, should use functions from v2"))
     E       UserWarning: api v1, should use functions from v2
-    
+
     test_show_warnings.py:4: UserWarning
     1 failed in 0.12 seconds
 
 The same option can be set in the ``pytest.ini`` file using the ``filterwarnings`` ini option.
 For example, the configuration below will ignore all user warnings, but will transform
 all other warnings into errors.
 
 .. code-block:: ini
@@ -73,49 +73,60 @@ all other warnings into errors.
 
 When a warning matches more than one option in the list, the action for the last matching option
 is performed.
 
 Both ``-W`` command-line option and ``filterwarnings`` ini option are based on Python's own
 `-W option`_ and `warnings.simplefilter`_, so please refer to those sections in the Python
 documentation for other examples and advanced usage.
 
+
+.. _`filterwarnings`:
+
 ``@pytest.mark.filterwarnings``
 -------------------------------
 
 .. versionadded:: 3.2
 
 You can use the ``@pytest.mark.filterwarnings`` to add warning filters to specific test items,
 allowing you to have finer control of which warnings should be captured at test, class or
 even module level:
 
 .. code-block:: python
 
     import warnings
 
+
     def api_v1():
         warnings.warn(UserWarning("api v1, should use functions from v2"))
         return 1
 
-    @pytest.mark.filterwarnings('ignore:api v1')
+
+    @pytest.mark.filterwarnings("ignore:api v1")
     def test_one():
         assert api_v1() == 1
 
 
 Filters applied using a mark take precedence over filters passed on the command line or configured
 by the ``filterwarnings`` ini option.
 
 You may apply a filter to all tests of a class by using the ``filterwarnings`` mark as a class
 decorator or to all tests in a module by setting the ``pytestmark`` variable:
 
 .. code-block:: python
 
     # turns all warnings into errors for this module
-    pytestmark = pytest.mark.filterwarnings('error')
+    pytestmark = pytest.mark.filterwarnings("error")
+
 
+.. note::
+
+    Except for these features, pytest does not change the python warning filter; it only captures
+    and displays the warnings which are issued with respect to the currently configured filter,
+    including changes to the filter made by test functions or by the system under test.
 
 .. note::
 
     ``DeprecationWarning`` and ``PendingDeprecationWarning`` are hidden by the standard library
     by default so you have to explicitly configure them to be displayed in your ``pytest.ini``:
 
     .. code-block:: ini
 
@@ -239,33 +250,21 @@ The ``recwarn`` fixture will record warn
         assert issubclass(w.category, UserWarning)
         assert str(w.message) == "hello"
         assert w.filename
         assert w.lineno
 
 Both ``recwarn`` and ``pytest.warns`` return the same interface for recorded
 warnings: a WarningsRecorder instance. To view the recorded warnings, you can
 iterate over this instance, call ``len`` on it to get the number of recorded
-warnings, or index into it to get a particular recorded warning. It also
-provides these methods:
-
-.. autoclass:: _pytest.recwarn.WarningsRecorder()
-    :members:
+warnings, or index into it to get a particular recorded warning.
 
-Each recorded warning has the attributes ``message``, ``category``,
-``filename``, ``lineno``, ``file``, and ``line``. The ``category`` is the
-class of the warning. The ``message`` is the warning itself; calling
-``str(message)`` will return the actual message of the warning.
+.. currentmodule:: _pytest.warnings
 
-.. note::
-    :class:`RecordedWarning` was changed from a plain class to a namedtuple in pytest 3.1
-
-.. note::
-    ``DeprecationWarning`` and ``PendingDeprecationWarning`` are treated
-    differently; see :ref:`ensuring_function_triggers`.
+Full API: :class:`WarningsRecorder`.
 
 .. _`ensuring a function triggers a deprecation warning`:
 
 .. _ensuring_function_triggers:
 
 Ensuring a function triggers a deprecation warning
 -------------------------------------------------------
 
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/writing_plugins.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/writing_plugins.rst
@@ -7,19 +7,19 @@ Writing plugins
 It is easy to implement `local conftest plugins`_ for your own project
 or `pip-installable plugins`_ that can be used throughout many projects,
 including third party projects.  Please refer to :ref:`using plugins` if you
 only want to use but not write plugins.
 
 A plugin contains one or multiple hook functions. :ref:`Writing hooks <writinghooks>`
 explains the basics and details of how you can write a hook function yourself.
 ``pytest`` implements all aspects of configuration, collection, running and
-reporting by calling `well specified hooks`_ of the following plugins:
+reporting by calling :ref:`well specified hooks <hook-reference>` of the following plugins:
 
-* :ref:`builtin plugins`: loaded from pytest's internal ``_pytest`` directory.
+* builtin plugins: loaded from pytest's internal ``_pytest`` directory.
 
 * :ref:`external plugins <extplugins>`: modules discovered through
   `setuptools entry points`_
 
 * `conftest.py plugins`_: modules auto-discovered in test directories
 
 In principle, each hook call is a ``1:N`` Python function call where ``N`` is the
 number of registered implementation functions for a given specification.
@@ -80,44 +80,44 @@ sub directory but not for other director
             pass
 
     test_flat.py:
         def test_flat():
             pass
 
 Here is how you might run it::
 
-     pytest test_flat.py   # will not show "setting up"
-     pytest a/test_sub.py  # will show "setting up"
+     pytest test_flat.py --capture=no  # will not show "setting up"
+     pytest a/test_sub.py --capture=no  # will show "setting up"
 
 .. note::
     If you have ``conftest.py`` files which do not reside in a
     python package directory (i.e. one containing an ``__init__.py``) then
     "import conftest" can be ambiguous because there might be other
     ``conftest.py`` files as well on your ``PYTHONPATH`` or ``sys.path``.
     It is thus good practice for projects to either put ``conftest.py``
     under a package scope or to never import anything from a
     ``conftest.py`` file.
 
     See also: :ref:`pythonpath`.
 
 
 Writing your own plugin
 -----------------------
 
-.. _`setuptools`: http://pypi.python.org/pypi/setuptools
+.. _`setuptools`: https://pypi.org/project/setuptools/
 
 If you want to write a plugin, there are many real-life examples
 you can copy from:
 
 * a custom collection example plugin: :ref:`yaml plugin`
-* around 20 :ref:`builtin plugins` which provide pytest's own functionality
+* builtin plugins which provide pytest's own functionality
 * many `external plugins <http://plugincompat.herokuapp.com>`_ providing additional features
 
-All of these plugins implement the documented `well specified hooks`_
+All of these plugins implement :ref:`hooks <hook-reference>` and/or :ref:`fixtures <fixture>`
 to extend and add functionality.
 
 .. note::
     Make sure to check out the excellent
     `cookiecutter-pytest-plugin <https://github.com/pytest-dev/cookiecutter-pytest-plugin>`_
     project, which is a `cookiecutter template <https://github.com/audreyr/cookiecutter>`_
     for authoring plugins.
 
@@ -145,42 +145,36 @@ it in your setuptools-invocation:
 
 .. sourcecode:: python
 
     # sample ./setup.py file
     from setuptools import setup
 
     setup(
         name="myproject",
-        packages = ['myproject']
-
+        packages=["myproject"],
         # the following makes a plugin available to pytest
-        entry_points = {
-            'pytest11': [
-                'name_of_plugin = myproject.pluginmodule',
-            ]
-        },
-
+        entry_points={"pytest11": ["name_of_plugin = myproject.pluginmodule"]},
         # custom PyPI classifier for pytest plugins
-        classifiers=[
-            "Framework :: Pytest",
-        ],
+        classifiers=["Framework :: Pytest"],
     )
 
 If a package is installed this way, ``pytest`` will load
 ``myproject.pluginmodule`` as a plugin which can define
-`well specified hooks`_.
+:ref:`hooks <hook-reference>`.
 
 .. note::
 
     Make sure to include ``Framework :: Pytest`` in your list of
     `PyPI classifiers <https://python-packaging-user-guide.readthedocs.io/distributing/#classifiers>`_
     to make it easy for users to find your plugin.
 
 
+.. _assertion-rewriting:
+
 Assertion Rewriting
 -------------------
 
 One of the main features of ``pytest`` is the use of plain assert
 statements and the detailed introspection of expressions upon
 assertion failures.  This is provided by "assertion rewriting" which
 modifies the parsed AST before it gets compiled to bytecode.  This is
 done via a :pep:`302` import hook which gets installed early on when
@@ -191,50 +185,47 @@ themselves as well as any modules which 
 other imported module will not be rewritten and normal assertion
 behaviour will happen.
 
 If you have assertion helpers in other modules where you would need
 assertion rewriting to be enabled you need to ask ``pytest``
 explicitly to rewrite this module before it gets imported.
 
 .. autofunction:: pytest.register_assert_rewrite
+    :noindex:
 
 This is especially important when you write a pytest plugin which is
 created using a package.  The import hook only treats ``conftest.py``
 files and any modules which are listed in the ``pytest11`` entrypoint
 as plugins.  As an example consider the following package::
 
    pytest_foo/__init__.py
    pytest_foo/plugin.py
    pytest_foo/helper.py
 
 With the following typical ``setup.py`` extract:
 
 .. code-block:: python
 
-   setup(
-      ...
-      entry_points={'pytest11': ['foo = pytest_foo.plugin']},
-      ...
-   )
+   setup(..., entry_points={"pytest11": ["foo = pytest_foo.plugin"]}, ...)
 
 In this case only ``pytest_foo/plugin.py`` will be rewritten.  If the
 helper module also contains assert statements which need to be
 rewritten it needs to be marked as such, before it gets imported.
 This is easiest by marking it for rewriting inside the
 ``__init__.py`` module, which will always be imported first when a
 module inside a package is imported.  This way ``plugin.py`` can still
 import ``helper.py`` normally.  The contents of
 ``pytest_foo/__init__.py`` will then need to look like this:
 
 .. code-block:: python
 
    import pytest
 
-   pytest.register_assert_rewrite('pytest_foo.helper')
+   pytest.register_assert_rewrite("pytest_foo.helper")
 
 
 
 Requiring/Loading plugins in a test module or conftest file
 -----------------------------------------------------------
 
 You can require plugins in a test module or a ``conftest.py`` file like this:
 
@@ -249,16 +240,28 @@ application modules:
 .. code-block:: python
 
     pytest_plugins = "myapp.testsupport.myplugin"
 
 ``pytest_plugins`` variables are processed recursively, so note that in the example above
 if ``myapp.testsupport.myplugin`` also declares ``pytest_plugins``, the contents
 of the variable will also be loaded as plugins, and so on.
 
+.. _`requiring plugins in non-root conftests`:
+
+.. note::
+    Requiring plugins using a ``pytest_plugins`` variable in non-root
+    ``conftest.py`` files is deprecated.
+
+    This is important because ``conftest.py`` files implement per-directory
+    hook implementations, but once a plugin is imported, it will affect the
+    entire directory tree. In order to avoid confusion, defining
+    ``pytest_plugins`` in any ``conftest.py`` file which is not located in the
+    tests root directory is deprecated, and will raise a warning.
+
 This mechanism makes it easy to share fixtures within applications or even
 external applications without the need to create external plugins using
 the ``setuptools``'s entry point technique.
 
 Plugins imported by ``pytest_plugins`` will also automatically be marked
 for assertion rewriting (see :func:`pytest.register_assert_rewrite`).
 However for this to have any effect the module must not be
 imported already; if it was already imported at the time the
@@ -273,17 +276,17 @@ Accessing another plugin by name
 --------------------------------
 
 If a plugin wants to collaborate with code from
 another plugin it can obtain a reference through
 the plugin manager like this:
 
 .. sourcecode:: python
 
-    plugin = config.pluginmanager.getplugin("name_of_plugin")
+    plugin = config.pluginmanager.get_plugin("name_of_plugin")
 
 If you want to look at the names of existing plugins, use
 the ``--trace-config`` option.
 
 Testing plugins
 ---------------
 
 pytest comes with a plugin named ``pytester`` that helps you write tests for
@@ -312,68 +315,74 @@ string value of ``Hello World!`` if we d
 {value}!`` if we do supply a string value.
 
 .. code-block:: python
 
     # -*- coding: utf-8 -*-
 
     import pytest
 
+
     def pytest_addoption(parser):
-        group = parser.getgroup('helloworld')
+        group = parser.getgroup("helloworld")
         group.addoption(
-            '--name',
-            action='store',
-            dest='name',
-            default='World',
-            help='Default "name" for hello().'
+            "--name",
+            action="store",
+            dest="name",
+            default="World",
+            help='Default "name" for hello().',
         )
 
+
     @pytest.fixture
     def hello(request):
-        name = request.config.getoption('name')
+        name = request.config.getoption("name")
 
         def _hello(name=None):
             if not name:
-                name = request.config.getoption('name')
+                name = request.config.getoption("name")
             return "Hello {name}!".format(name=name)
 
         return _hello
 
 
 Now the ``testdir`` fixture provides a convenient API for creating temporary
 ``conftest.py`` files and test files. It also allows us to run the tests and
 return a result object, with which we can assert the tests' outcomes.
 
 .. code-block:: python
 
     def test_hello(testdir):
         """Make sure that our plugin works."""
 
         # create a temporary conftest.py file
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture(params=[
                 "Brianna",
                 "Andreas",
                 "Floris",
             ])
             def name(request):
                 return request.param
-        """)
+        """
+        )
 
         # create a temporary pytest test file
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_hello_default(hello):
                 assert hello() == "Hello World!"
 
             def test_hello_name(hello, name):
                 assert hello(name) == "Hello {0}!".format(name)
-        """)
+        """
+        )
 
         # run all tests with pytest
         result = testdir.runpytest()
 
         # check that all 4 tests passed
         result.assert_outcomes(passed=4)
 
 
@@ -405,16 +414,17 @@ names which match the specification and 
 
 Let's look at a possible implementation:
 
 .. code-block:: python
 
     def pytest_collection_modifyitems(config, items):
         # called after collection is completed
         # you can modify the ``items`` list
+        ...
 
 Here, ``pytest`` will pass in ``config`` (the pytest config object)
 and ``items`` (the list of collected test items) but will not pass
 in the ``session`` argument because we didn't list it in the function
 signature.  This dynamic "pruning" of arguments allows ``pytest`` to
 be "future-compatible": we can introduce new hook named parameters without
 breaking the signatures of existing hook implementations.  It is one of
 the reasons for the general long-lived compatibility of pytest plugins.
@@ -457,50 +467,59 @@ exception info.  The yield point itself 
 exceptions (unless there are bugs).
 
 Here is an example definition of a hook wrapper::
 
     import pytest
 
     @pytest.hookimpl(hookwrapper=True)
     def pytest_pyfunc_call(pyfuncitem):
-        # do whatever you want before the next hook executes
+        do_something_before_next_hook_executes()
 
         outcome = yield
         # outcome.excinfo may be None or a (cls, val, tb) tuple
 
         res = outcome.get_result()  # will raise if outcome was exception
-        # postprocess result
+
+        post_process_result(res)
+
+        outcome.force_result(new_res)  # to override the return value to the plugin system
 
 Note that hook wrappers don't return results themselves, they merely
 perform tracing or other side effects around the actual hook implementations.
 If the result of the underlying hook is a mutable object, they may modify
 that result but it's probably better to avoid it.
 
+For more information, consult the `pluggy documentation <http://pluggy.readthedocs.io/en/latest/#wrappers>`_.
+
 
 Hook function ordering / call example
 -------------------------------------
 
 For any given hook specification there may be more than one
 implementation and we thus generally view ``hook`` execution as a
 ``1:N`` function call where ``N`` is the number of registered functions.
 There are ways to influence if a hook implementation comes before or
 after others, i.e.  the position in the ``N``-sized list of functions:
 
 .. code-block:: python
 
     # Plugin 1
     @pytest.hookimpl(tryfirst=True)
     def pytest_collection_modifyitems(items):
         # will execute as early as possible
+        ...
+
 
     # Plugin 2
     @pytest.hookimpl(trylast=True)
     def pytest_collection_modifyitems(items):
         # will execute as late as possible
+        ...
+
 
     # Plugin 3
     @pytest.hookimpl(hookwrapper=True)
     def pytest_collection_modifyitems(items):
         # will execute even before the tryfirst one above!
         outcome = yield
         # will execute after all non-hookwrappers executed
 
@@ -530,16 +549,17 @@ Declaring new hooks
 
 .. currentmodule:: _pytest.hookspec
 
 Plugins and ``conftest.py`` files may declare new hooks that can then be
 implemented by other plugins in order to alter behaviour or interact with
 the new plugin:
 
 .. autofunction:: pytest_addhooks
+    :noindex:
 
 Hooks are usually declared as do-nothing functions that contain only
 documentation describing when the hook will be called and what return values
 are expected.
 
 For an example, see `newhooks.py`_ from `xdist <https://github.com/pytest-dev/pytest-xdist>`_.
 
 .. _`newhooks.py`: https://github.com/pytest-dev/pytest-xdist/blob/974bd566c599dc6a9ea291838c6f226197208b46/xdist/newhooks.py
@@ -566,174 +586,8 @@ declaring the hook functions directly in
             """
 
     def pytest_configure(config):
         if config.pluginmanager.hasplugin('xdist'):
             config.pluginmanager.register(DeferPlugin())
 
 This has the added benefit of allowing you to conditionally install hooks
 depending on which plugins are installed.
-
-.. _`well specified hooks`:
-
-.. currentmodule:: _pytest.hookspec
-
-pytest hook reference
-=====================
-
-
-Initialization, command line and configuration hooks
-----------------------------------------------------
-
-.. autofunction:: pytest_load_initial_conftests
-.. autofunction:: pytest_cmdline_preparse
-.. autofunction:: pytest_cmdline_parse
-.. autofunction:: pytest_addoption
-.. autofunction:: pytest_cmdline_main
-.. autofunction:: pytest_configure
-.. autofunction:: pytest_unconfigure
-
-Generic "runtest" hooks
------------------------
-
-All runtest related hooks receive a :py:class:`pytest.Item <_pytest.main.Item>` object.
-
-.. autofunction:: pytest_runtest_protocol
-.. autofunction:: pytest_runtest_setup
-.. autofunction:: pytest_runtest_call
-.. autofunction:: pytest_runtest_teardown
-.. autofunction:: pytest_runtest_makereport
-
-For deeper understanding you may look at the default implementation of
-these hooks in :py:mod:`_pytest.runner` and maybe also
-in :py:mod:`_pytest.pdb` which interacts with :py:mod:`_pytest.capture`
-and its input/output capturing in order to immediately drop
-into interactive debugging when a test failure occurs.
-
-The :py:mod:`_pytest.terminal` reported specifically uses
-the reporting hook to print information about a test run.
-
-Collection hooks
-----------------
-
-``pytest`` calls the following hooks for collecting files and directories:
-
-.. autofunction:: pytest_ignore_collect
-.. autofunction:: pytest_collect_directory
-.. autofunction:: pytest_collect_file
-
-For influencing the collection of objects in Python modules
-you can use the following hook:
-
-.. autofunction:: pytest_pycollect_makeitem
-.. autofunction:: pytest_generate_tests
-.. autofunction:: pytest_make_parametrize_id
-
-After collection is complete, you can modify the order of
-items, delete or otherwise amend the test items:
-
-.. autofunction:: pytest_collection_modifyitems
-
-Reporting hooks
----------------
-
-Session related reporting hooks:
-
-.. autofunction:: pytest_collectstart
-.. autofunction:: pytest_itemcollected
-.. autofunction:: pytest_collectreport
-.. autofunction:: pytest_deselected
-.. autofunction:: pytest_report_header
-.. autofunction:: pytest_report_collectionfinish
-.. autofunction:: pytest_report_teststatus
-.. autofunction:: pytest_terminal_summary
-.. autofunction:: pytest_fixture_setup
-.. autofunction:: pytest_fixture_post_finalizer
-
-And here is the central hook for reporting about
-test execution:
-
-.. autofunction:: pytest_runtest_logreport
-
-You can also use this hook to customize assertion representation for some
-types:
-
-.. autofunction:: pytest_assertrepr_compare
-
-
-Debugging/Interaction hooks
----------------------------
-
-There are few hooks which can be used for special
-reporting or interaction with exceptions:
-
-.. autofunction:: pytest_internalerror
-.. autofunction:: pytest_keyboard_interrupt
-.. autofunction:: pytest_exception_interact
-.. autofunction:: pytest_enter_pdb
-
-
-Reference of objects involved in hooks
-======================================
-
-.. autoclass:: _pytest.config.Config()
-    :members:
-
-.. autoclass:: _pytest.config.Parser()
-    :members:
-
-.. autoclass:: _pytest.main.Node()
-    :members:
-
-.. autoclass:: _pytest.main.Collector()
-    :members:
-    :show-inheritance:
-
-.. autoclass:: _pytest.main.Item()
-    :members:
-    :show-inheritance:
-
-.. autoclass:: _pytest.python.Module()
-    :members:
-    :show-inheritance:
-
-.. autoclass:: _pytest.python.Class()
-    :members:
-    :show-inheritance:
-
-.. autoclass:: _pytest.python.Function()
-    :members:
-    :show-inheritance:
-
-.. autoclass:: _pytest.fixtures.FixtureDef()
-    :members:
-    :show-inheritance:
-
-.. autoclass:: _pytest.runner.CallInfo()
-    :members:
-
-.. autoclass:: _pytest.runner.TestReport()
-    :members:
-    :inherited-members:
-
-.. autoclass:: pluggy._Result
-    :members:
-
-.. autofunction:: _pytest.config.get_plugin_manager()
-
-.. autoclass:: _pytest.config.PytestPluginManager()
-    :members:
-    :undoc-members:
-    :show-inheritance:
-
-.. autoclass:: pluggy.PluginManager()
-    :members:
-
-.. currentmodule:: _pytest.pytester
-
-.. autoclass:: Testdir()
-    :members: runpytest,runpytest_subprocess,runpytest_inprocess,makeconftest,makepyfile
-
-.. autoclass:: RunResult()
-    :members:
-
-.. autoclass:: LineMatcher()
-    :members:
--- a/testing/web-platform/tests/tools/third_party/pytest/doc/en/xunit_setup.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/doc/en/xunit_setup.rst
@@ -1,17 +1,17 @@
 
 .. _`classic xunit`:
 .. _xunitsetup:
 
 classic xunit-style setup
 ========================================
 
 This section describes a classic and popular way how you can implement
-fixtures (setup and teardown test state) on a per-module/class/function basis.  
+fixtures (setup and teardown test state) on a per-module/class/function basis.
 
 
 .. note::
 
     While these setup/teardown methods are simple and familiar to those
     coming from a ``unittest`` or nose ``background``, you may also consider
     using pytest's more powerful :ref:`fixture mechanism
     <fixture>` which leverages the concept of dependency injection, allowing
--- a/testing/web-platform/tests/tools/third_party/pytest/extra/get_issues.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/extra/get_issues.py
@@ -1,36 +1,34 @@
 import json
 import py
-import textwrap
+import requests
 
 issues_url = "https://api.github.com/repos/pytest-dev/pytest/issues"
 
-import requests
-
 
 def get_issues():
     issues = []
     url = issues_url
     while 1:
         get_data = {"state": "all"}
         r = requests.get(url, params=get_data)
         data = r.json()
         if r.status_code == 403:
             # API request limit exceeded
-            print(data['message'])
+            print(data["message"])
             exit(1)
         issues.extend(data)
 
         # Look for next page
-        links = requests.utils.parse_header_links(r.headers['Link'])
+        links = requests.utils.parse_header_links(r.headers["Link"])
         another_page = False
         for link in links:
-            if link['rel'] == 'next':
-                url = link['url']
+            if link["rel"] == "next":
+                url = link["url"]
                 another_page = True
         if not another_page:
             return issues
 
 
 def main(args):
     cachefile = py.path.local(args.cache)
     if not cachefile.exists() or args.refresh:
@@ -41,44 +39,46 @@ def main(args):
 
     open_issues = [x for x in issues if x["state"] == "open"]
 
     open_issues.sort(key=lambda x: x["number"])
     report(open_issues)
 
 
 def _get_kind(issue):
-    labels = [l['name'] for l in issue['labels']]
-    for key in ('bug', 'enhancement', 'proposal'):
+    labels = [l["name"] for l in issue["labels"]]
+    for key in ("bug", "enhancement", "proposal"):
         if key in labels:
             return key
-    return 'issue'
+    return "issue"
 
 
 def report(issues):
     for issue in issues:
         title = issue["title"]
-        body = issue["body"]
+        # body = issue["body"]
         kind = _get_kind(issue)
         status = issue["state"]
         number = issue["number"]
         link = "https://github.com/pytest-dev/pytest/issues/%s/" % number
         print("----")
         print(status, kind, link)
         print(title)
-        #print()
-        #lines = body.split("\n")
-        #print ("\n".join(lines[:3]))
-        #if len(lines) > 3 or len(body) > 240:
+        # print()
+        # lines = body.split("\n")
+        # print ("\n".join(lines[:3]))
+        # if len(lines) > 3 or len(body) > 240:
         #    print ("...")
     print("\n\nFound %s open issues" % len(issues))
 
 
 if __name__ == "__main__":
     import argparse
+
     parser = argparse.ArgumentParser("process bitbucket issues")
-    parser.add_argument("--refresh", action="store_true",
-                        help="invalidate cache, refresh issues")
-    parser.add_argument("--cache", action="store", default="issues.json",
-                        help="cache file")
+    parser.add_argument(
+        "--refresh", action="store_true", help="invalidate cache, refresh issues"
+    )
+    parser.add_argument(
+        "--cache", action="store", default="issues.json", help="cache file"
+    )
     args = parser.parse_args()
     main(args)
-
--- a/testing/web-platform/tests/tools/third_party/pytest/pyproject.toml
+++ b/testing/web-platform/tests/tools/third_party/pytest/pyproject.toml
@@ -1,10 +1,18 @@
+[build-system]
+requires = [
+  "setuptools",
+  "setuptools-scm",
+  "wheel",
+]
+
 [tool.towncrier]
 package = "pytest"
+package_dir = "src"
 filename = "CHANGELOG.rst"
 directory = "changelog/"
 template = "changelog/_template.rst"
 
   [[tool.towncrier.type]]
   directory = "removal"
   name = "Deprecations and Removals"
   showcontent = true
deleted file mode 100644
--- a/testing/web-platform/tests/tools/third_party/pytest/scripts/check-rst.py
+++ /dev/null
@@ -1,11 +0,0 @@
-
-from __future__ import print_function
-
-import subprocess
-import glob
-import sys
-
-sys.exit(subprocess.call([
-    'rst-lint', '--encoding', 'utf-8',
-    'CHANGELOG.rst', 'HOWTORELEASE.rst', 'README.rst',
-] + glob.glob('changelog/[0-9]*.*')))
--- a/testing/web-platform/tests/tools/third_party/pytest/setup.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/setup.py
@@ -1,114 +1,124 @@
 import os
 import sys
 import setuptools
 import pkg_resources
-from setuptools import setup, Command
+from setuptools import setup
 
 classifiers = [
-    'Development Status :: 6 - Mature',
-    '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',
+    "Development Status :: 6 - Mature",
+    "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 :: %s' % x)
-    for x in '2 2.7 3 3.4 3.5 3.6'.split()
+    ("Programming Language :: Python :: %s" % x)
+    for x in "2 2.7 3 3.4 3.5 3.6 3.7".split()
 ]
 
-with open('README.rst') as fd:
+with open("README.rst") as fd:
     long_description = fd.read()
 
 
-def has_environment_marker_support():
+def get_environment_marker_support_level():
     """
-    Tests that setuptools has support for PEP-426 environment marker support.
+    Tests how well setuptools supports PEP-426 environment marker.
 
     The first known release to support it is 0.7 (and the earliest on PyPI seems to be 0.7.2
-    so we're using that), see: http://pythonhosted.org/setuptools/history.html#id142
+    so we're using that), see: https://setuptools.readthedocs.io/en/latest/history.html#id350
+
+    The support is later enhanced to allow direct conditional inclusions inside install_requires,
+    which is now recommended by setuptools. It first appeared in 36.2.0, went broken with 36.2.1, and
+    again worked since 36.2.2, so we're using that. See:
+    https://setuptools.readthedocs.io/en/latest/history.html#v36-2-2
+    https://github.com/pypa/setuptools/issues/1099
 
     References:
 
     * https://wheel.readthedocs.io/en/latest/index.html#defining-conditional-dependencies
     * https://www.python.org/dev/peps/pep-0426/#environment-markers
+    * https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
     """
     try:
-        return pkg_resources.parse_version(setuptools.__version__) >= pkg_resources.parse_version('0.7.2')
+        version = pkg_resources.parse_version(setuptools.__version__)
+        if version >= pkg_resources.parse_version("36.2.2"):
+            return 2
+        if version >= pkg_resources.parse_version("0.7.2"):
+            return 1
     except Exception as exc:
         sys.stderr.write("Could not test setuptool's version: %s\n" % exc)
-        return False
+
+    # as of testing on 2018-05-26 fedora was on version 37* and debian was on version 33+
+    # we should consider erroring on those
+    return 0
 
 
 def main():
     extras_require = {}
     install_requires = [
-        'py>=1.5.0',
-        'six>=1.10.0',
-        'setuptools',
-        'attrs>=17.2.0',
+        "py>=1.5.0",
+        "six>=1.10.0",
+        "setuptools",
+        "attrs>=17.4.0",
+        "more-itertools>=4.0.0",
+        "atomicwrites>=1.0",
     ]
     # if _PYTEST_SETUP_SKIP_PLUGGY_DEP is set, skip installing pluggy;
     # used by tox.ini to test with pluggy master
-    if '_PYTEST_SETUP_SKIP_PLUGGY_DEP' not in os.environ:
-        install_requires.append('pluggy>=0.5,<0.7')
-    if has_environment_marker_support():
-        extras_require[':python_version<"3.0"'] = ['funcsigs']
-        extras_require[':sys_platform=="win32"'] = ['colorama']
+    if "_PYTEST_SETUP_SKIP_PLUGGY_DEP" not in os.environ:
+        install_requires.append("pluggy>=0.5,<0.7")
+    environment_marker_support_level = get_environment_marker_support_level()
+    if environment_marker_support_level >= 2:
+        install_requires.append('funcsigs;python_version<"3.0"')
+        install_requires.append('colorama;sys_platform=="win32"')
+    elif environment_marker_support_level == 1:
+        extras_require[':python_version<"3.0"'] = ["funcsigs"]
+        extras_require[':sys_platform=="win32"'] = ["colorama"]
     else:
-        if sys.platform == 'win32':
-            install_requires.append('colorama')
+        if sys.platform == "win32":
+            install_requires.append("colorama")
         if sys.version_info < (3, 0):
-            install_requires.append('funcsigs')
+            install_requires.append("funcsigs")
 
     setup(
-        name='pytest',
-        description='pytest: simple powerful testing with Python',
+        name="pytest",
+        description="pytest: simple powerful testing with Python",
         long_description=long_description,
-        use_scm_version={
-            'write_to': '_pytest/_version.py',
+        use_scm_version={"write_to": "src/_pytest/_version.py"},
+        url="http://pytest.org",
+        project_urls={
+            "Source": "https://github.com/pytest-dev/pytest",
+            "Tracker": "https://github.com/pytest-dev/pytest/issues",
         },
-        url='http://pytest.org',
-        license='MIT license',
-        platforms=['unix', 'linux', 'osx', 'cygwin', 'win32'],
+        license="MIT license",
+        platforms=["unix", "linux", "osx", "cygwin", "win32"],
         author=(
-            'Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, '
-            'Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others'),
-        entry_points={'console_scripts': [
-            'pytest=pytest:main', 'py.test=pytest:main']},
+            "Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, "
+            "Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others"
+        ),
+        entry_points={"console_scripts": ["pytest=pytest:main", "py.test=pytest:main"]},
         classifiers=classifiers,
         keywords="test unittest",
-        cmdclass={'test': PyTest},
         # the following should be enabled for release
-        setup_requires=['setuptools-scm'],
-        python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
+        setup_requires=["setuptools-scm"],
+        package_dir={"": "src"},
+        python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
         install_requires=install_requires,
         extras_require=extras_require,
-        packages=['_pytest', '_pytest.assertion', '_pytest._code'],
-        py_modules=['pytest'],
+        packages=[
+            "_pytest",
+            "_pytest.assertion",
+            "_pytest._code",
+            "_pytest.mark",
+            "_pytest.config",
+        ],
+        py_modules=["pytest"],
         zip_safe=False,
     )
 
 
-class PyTest(Command):
-    user_options = []
-
-    def initialize_options(self):
-        pass
-
-    def finalize_options(self):
-        pass
-
-    def run(self):
-        import subprocess
-        PPATH = [x for x in os.environ.get('PYTHONPATH', '').split(':') if x]
-        PPATH.insert(0, os.getcwd())
-        os.environ['PYTHONPATH'] = ':'.join(PPATH)
-        errno = subprocess.call([sys.executable, 'pytest.py', '--ignore=doc'])
-        raise SystemExit(errno)
-
-
-if __name__ == '__main__':
+if __name__ == "__main__":
     main()
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/__init__.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/__init__.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/__init__.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/__init__.py
@@ -1,8 +1,8 @@
-__all__ = ['__version__']
+__all__ = ["__version__"]
 
 try:
     from ._version import version as __version__
 except ImportError:
     # broken installation, we don't even try
     # unknown only works because we do poor mans version compare
-    __version__ = 'unknown'
+    __version__ = "unknown"
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/_argcomplete.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/_argcomplete.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/_argcomplete.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/_argcomplete.py
@@ -55,49 +55,53 @@ If things do not work right away:
   global argcomplete script).
 """
 from __future__ import absolute_import, division, print_function
 import sys
 import os
 from glob import glob
 
 
-class FastFilesCompleter:
-    'Fast file completer class'
+class FastFilesCompleter(object):
+    "Fast file completer class"
 
     def __init__(self, directories=True):
         self.directories = directories
 
     def __call__(self, prefix, **kwargs):
         """only called on non option completions"""
         if os.path.sep in prefix[1:]:
             prefix_dir = len(os.path.dirname(prefix) + os.path.sep)
         else:
             prefix_dir = 0
         completion = []
         globbed = []
-        if '*' not in prefix and '?' not in prefix:
+        if "*" not in prefix and "?" not in prefix:
             # we are on unix, otherwise no bash
             if not prefix or prefix[-1] == os.path.sep:
-                globbed.extend(glob(prefix + '.*'))
-            prefix += '*'
+                globbed.extend(glob(prefix + ".*"))
+            prefix += "*"
         globbed.extend(glob(prefix))
         for x in sorted(globbed):
             if os.path.isdir(x):
-                x += '/'
+                x += "/"
             # append stripping the prefix (like bash, not like compgen)
             completion.append(x[prefix_dir:])
         return completion
 
 
-if os.environ.get('_ARGCOMPLETE'):
+if os.environ.get("_ARGCOMPLETE"):
     try:
         import argcomplete.completers
     except ImportError:
         sys.exit(-1)
     filescompleter = FastFilesCompleter()
 
     def try_argcomplete(parser):
         argcomplete.autocomplete(parser, always_complete_options=False)
+
+
 else:
+
     def try_argcomplete(parser):
         pass
+
     filescompleter = None
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/_code/__init__.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/_code/__init__.py
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/_code/_py2traceback.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/_code/_py2traceback.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/_code/_py2traceback.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/_code/_py2traceback.py
@@ -1,14 +1,15 @@
 # copied from python-2.7.3's traceback.py
 # CHANGES:
 # - some_str is replaced, trying to create unicode strings
 #
 from __future__ import absolute_import, division, print_function
 import types
+from six import text_type
 
 
 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.
@@ -24,19 +25,22 @@ def format_exception_only(etype, value):
     """
 
     # 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):
+    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.
@@ -45,24 +49,24 @@ def format_exception_only(etype, value):
         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())
+                badline = badline.decode("utf-8", "replace")
+            lines.append(u"    %s\n" % badline.strip())
             if offset is not None:
-                caretspace = badline.rstrip('\n')[:offset].lstrip()
+                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)
+                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))
+                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"""
@@ -71,15 +75,15 @@ def _format_final_exc_line(etype, value)
         line = "%s\n" % etype
     else:
         line = "%s: %s\n" % (etype, valuestr)
     return line
 
 
 def _some_str(value):
     try:
-        return unicode(value)
+        return text_type(value)
     except Exception:
         try:
             return str(value)
         except Exception:
             pass
-    return '<unprintable %s object>' % type(value).__name__
+    return "<unprintable %s object>" % type(value).__name__
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/_code/code.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/_code/code.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/_code/code.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/_code/code.py
@@ -1,16 +1,21 @@
 from __future__ import absolute_import, division, print_function
+import inspect
 import sys
+import traceback
 from inspect import CO_VARARGS, CO_VARKEYWORDS
+
+import attr
 import re
 from weakref import ref
 from _pytest.compat import _PY2, _PY3, PY35, safe_str
+from six import text_type
+import py
 
-import py
 builtin_repr = repr
 
 if _PY3:
     from traceback import format_exception_only
 else:
     from ._py2traceback import format_exception_only
 
 
@@ -52,24 +57,26 @@ class Code(object):
 
         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
         """
@@ -92,16 +99,17 @@ class Frame(object):
         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
@@ -135,17 +143,17 @@ class Frame(object):
             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
+                pass  # this can occur when using Psyco
         return retval
 
 
 class TracebackEntry(object):
     """ a single entry in a traceback """
 
     _repr_style = None
     exprinfo = None
@@ -157,16 +165,17 @@ class TracebackEntry(object):
 
     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)
@@ -179,39 +188,42 @@ class TracebackEntry(object):
 
     @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)
+            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)
@@ -221,61 +233,64 @@ class TracebackEntry(object):
             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__']
+            tbh = self.frame.f_locals["__tracebackhide__"]
         except KeyError:
             try:
-                tbh = self.frame.f_globals['__tracebackhide__']
+                tbh = self.frame.f_globals["__tracebackhide__"]
             except KeyError:
                 return False
 
         if callable(tbh):
             return tbh(None if self._excinfo is None else self._excinfo())
         else:
             return tbh
 
     def __str__(self):
         try:
             fn = str(self.path)
         except py.error.Error:
-            fn = '???'
+            fn = "???"
         name = self.frame.code.name
         try:
             line = str(self.statement).lstrip()
         except KeyboardInterrupt:
             raise
         except:  # noqa
             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'):
+        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
@@ -283,21 +298,26 @@ class Traceback(list):
 
             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)):
+            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
@@ -336,45 +356,51 @@ class Traceback(list):
             # XXX needs a test
             key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno
             # print "checking for recursion at", key
             values = cache.setdefault(key, [])
             if values:
                 f = entry.frame
                 loc = f.f_locals
                 for otherloc in values:
-                    if f.is_true(f.eval(co_equal,
-                                        __recursioncache_locals_1=loc,
-                                        __recursioncache_locals_2=otherloc)):
+                    if f.is_true(
+                        f.eval(
+                            co_equal,
+                            __recursioncache_locals_1=loc,
+                            __recursioncache_locals_2=otherloc,
+                        )
+                    ):
                         return i
             values.append(entry.frame.f_locals)
         return None
 
 
-co_equal = compile('__recursioncache_locals_1 == __recursioncache_locals_2',
-                   '?', 'eval')
+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 = ''
-    _assert_start_repr = "AssertionError(u\'assert " if _PY2 else "AssertionError(\'assert "
+    _striptext = ""
+    _assert_start_repr = "AssertionError(u'assert " if _PY2 else "AssertionError('assert "
 
     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)
+                exprinfo = getattr(tup[1], "msg", None)
                 if exprinfo is None:
                     exprinfo = py.io.saferepr(tup[1])
                 if exprinfo and exprinfo.startswith(self._assert_start_repr):
-                    self._striptext = 'AssertionError: '
+                    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
@@ -389,91 +415,103 @@ class ExceptionInfo(object):
         """ 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 = "".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):
+    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())
+        if style == "native":
+            return ReprExceptionInfo(
+                ReprTracebackNative(
+                    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)
+        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)
+        return text_type(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)
+            assert 0, "Pattern '{!s}' not found in '{!s}'".format(regexp, self.value)
         return True
 
 
+@attr.s
 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 = {}
+    showlocals = attr.ib(default=False)
+    style = attr.ib(default="long")
+    abspath = attr.ib(default=True)
+    tbfilter = attr.ib(default=True)
+    funcargs = attr.ib(default=False)
+    astcache = attr.ib(default=attr.Factory(dict), init=False, repr=False)
 
     def _getindent(self, source):
         # figure out indent for given source
         try:
             s = str(source.getstatement(len(source) - 1))
         except KeyboardInterrupt:
             raise
         except:  # noqa
@@ -499,16 +537,17 @@ class FormattedExcinfo(object):
             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:
@@ -523,49 +562,50 @@ class FormattedExcinfo(object):
             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')
+        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__':
+                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)
+                    #    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)
 
@@ -632,21 +672,26 @@ class FormattedExcinfo(object):
         comparing numpy arrays using equality raises a TypeError), in which case we do our best to
         warn the user of the error and show a limited traceback.
         """
         try:
             recursionindex = traceback.recursionindex()
         except Exception as e:
             max_frames = 10
             extraline = (
-                '!!! Recursion error detected, but an error occurred locating the origin of recursion.\n'
-                '  The following exception happened when comparing locals in the stack frame:\n'
-                '    {exc_type}: {exc_msg}\n'
-                '  Displaying first and last {max_frames} stack frames out of {total}.'
-            ).format(exc_type=type(e).__name__, exc_msg=safe_str(e), max_frames=max_frames, total=len(traceback))
+                "!!! Recursion error detected, but an error occurred locating the origin of recursion.\n"
+                "  The following exception happened when comparing locals in the stack frame:\n"
+                "    {exc_type}: {exc_msg}\n"
+                "  Displaying first and last {max_frames} stack frames out of {total}."
+            ).format(
+                exc_type=type(e).__name__,
+                exc_msg=safe_str(e),
+                max_frames=max_frames,
+                total=len(traceback),
+            )
             traceback = traceback[:max_frames] + traceback[-max_frames:]
         else:
             if recursionindex is not None:
                 extraline = "!!! Recursion detected (same locals & position)"
                 traceback = traceback[:recursionindex + 1]
             else:
                 extraline = None
 
@@ -664,67 +709,76 @@ class FormattedExcinfo(object):
             descr = None
             while e is not None:
                 if excinfo:
                     reprtraceback = self.repr_traceback(excinfo)
                     reprcrash = excinfo._getreprcrash()
                 else:
                     # fallback to native repr if the exception doesn't have a traceback:
                     # ExceptionInfo objects require a full traceback to work
-                    reprtraceback = ReprTracebackNative(py.std.traceback.format_exception(type(e), e, None))
+                    reprtraceback = ReprTracebackNative(
+                        traceback.format_exception(type(e), e, None)
+                    )
                     reprcrash = None
 
                 repr_chain += [(reprtraceback, reprcrash, descr)]
                 if e.__cause__ is not None:
                     e = e.__cause__
-                    excinfo = ExceptionInfo((type(e), e, e.__traceback__)) if e.__traceback__ else None
-                    descr = 'The above exception was the direct cause of the following exception:'
+                    excinfo = ExceptionInfo(
+                        (type(e), e, e.__traceback__)
+                    ) if e.__traceback__ else None
+                    descr = "The above exception was the direct cause of the following exception:"
                 elif (e.__context__ is not None and not e.__suppress_context__):
                     e = e.__context__
-                    excinfo = ExceptionInfo((type(e), e, e.__traceback__)) if e.__traceback__ else None
-                    descr = 'During handling of the above exception, another exception occurred:'
+                    excinfo = ExceptionInfo(
+                        (type(e), e, e.__traceback__)
+                    ) if e.__traceback__ else None
+                    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 _PY2:
-            s = s.encode('utf-8')
+            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]
 
@@ -733,16 +787,17 @@ class ExceptionChainRepr(ExceptionRepr):
             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)
@@ -759,25 +814,29 @@ class ReprTraceback(TerminalRepr):
     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":
+                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"
@@ -817,22 +876,21 @@ class ReprEntry(TerminalRepr):
             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)
+        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
@@ -840,25 +898,27 @@ class ReprFileLocation(TerminalRepr):
         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" % (safe_str(name), safe_str(value))
@@ -876,31 +936,35 @@ class ReprFuncArgs(TerminalRepr):
             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):
+        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 inspect.isclass(obj):
                 x = getrawcode(obj.__call__, trycall=False)
-                if hasattr(x, 'co_firstlineno'):
+                if hasattr(x, "co_firstlineno"):
                     return x
         return obj
 
 
 if PY35:  # 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
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/_code/source.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/_code/source.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/_code/source.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/_code/source.py
@@ -1,45 +1,42 @@
 from __future__ import absolute_import, division, generators, print_function
 
+import ast
+from ast import PyCF_ONLY_AST as _AST_FLAG
 from bisect import bisect_right
+import linecache
 import sys
 import six
 import inspect
 import tokenize
 import py
+
 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,
+    """ an 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)
+        de = kwargs.get("deindent", True)
+        rstrip = kwargs.get("rstrip", True)
         for part in parts:
             if not part:
                 partlines = []
-            if isinstance(part, Source):
+            elif isinstance(part, Source):
                 partlines = part.lines
             elif isinstance(part, (tuple, list)):
                 partlines = [x.rstrip("\n") for x in part]
             elif isinstance(part, six.string_types):
-                partlines = part.split('\n')
+                partlines = part.split("\n")
                 if rstrip:
                     while partlines:
                         if partlines[-1].strip():
                             break
                         partlines.pop()
             else:
                 partlines = getsource(part, deindent=de).lines
             if de:
@@ -77,43 +74,43 @@ class Source(object):
         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):
+    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):
+    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):
+    def getstatement(self, lineno):
         """ return Source statement which contains the
             given linenumber (counted from 0).
         """
-        start, end = self.getstatementrange(lineno, assertion)
+        start, end = self.getstatementrange(lineno)
         return self[start:end]
 
-    def getstatementrange(self, lineno, assertion=False):
+    def getstatementrange(self, lineno):
         """ 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
 
@@ -129,151 +126,155 @@ class Source(object):
         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:
-            def syntax_checker(x):
-                return compile(x, 'asd', 'exec')
-        else:
-            syntax_checker = parser.suite
+        from parser import suite as syntax_checker
 
         if deindent:
             source = str(self.deindent())
         else:
             source = str(self)
         try:
             # compile(source+'\n', "x", "exec")
-            syntax_checker(source + '\n')
+            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):
+    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)
+                filename = base + "%s:%d>" % (fn, lineno)
             else:
-                filename = base + '%r %s:%d>' % (filename, fn, lineno)
-        source = "\n".join(self.lines) + '\n'
+                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(" " * ex.offset + "^")
             msglines.append("(code was compiled probably from here: %s)" % filename)
-            newex = SyntaxError('\n'.join(msglines))
+            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]
-            py.std.linecache.cache[filename] = (1, None, lines, filename)
+            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):
+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):
+    if 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
+    from .code import Code
+
     try:
-        code = _pytest._code.Code(obj)
+        code = Code(obj)
     except TypeError:
         try:
-            fn = (py.std.inspect.getsourcefile(obj) or
-                  py.std.inspect.getfile(obj))
+            fn = inspect.getsourcefile(obj) or 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)
+        sourcelines, lineno = inspect.findsource(obj)
     except py.builtin._sysex:
         raise
     except:  # noqa
         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)
+    from .code import getrawcode
+
+    obj = getrawcode(obj)
     try:
         strsrc = inspect.getsource(obj)
     except IndentationError:
-        strsrc = "\"Buggy python version consider upgrading, cannot get source\""
+        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()
@@ -284,24 +285,24 @@ def deindent(lines, offset=None):
         else:
             offset = 0
     if offset == 0:
         return list(lines)
     newlines = []
 
     def readline_generator(lines):
         for line in lines:
-            yield line + '\n'
-        while True:
-            yield ''
+            yield line + "\n"
 
     it = readline_generator(lines)
 
     try:
-        for _, _, (sline, _), (eline, _), _ in tokenize.generate_tokens(lambda: next(it)):
+        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)
 
@@ -313,23 +314,24 @@ def deindent(lines, offset=None):
         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
     values = []
     for x in ast.walk(node):
-        if isinstance(x, _ast.stmt) or isinstance(x, _ast.ExceptHandler):
+        if isinstance(x, (ast.stmt, ast.ExceptHandler)):
             values.append(x.lineno - 1)
-            for name in "finalbody", "orelse":
+            for name in ("finalbody", "orelse"):
                 val = getattr(x, name, None)
                 if val:
                     # treat the finally/orelse part as its own statement
                     values.append(val[0].lineno - 1 - 1)
     values.sort()
     insert_index = bisect_right(values, lineno)
     start = values[insert_index - 1]
     if insert_index >= len(values):
@@ -337,21 +339,18 @@ def get_statement_startend2(lineno, node
     else:
         end = values[insert_index]
     return start, end
 
 
 def getstatementrange_ast(lineno, source, assertion=False, astnode=None):
     if astnode is None:
         content = str(source)
-        try:
-            astnode = compile(content, "source", "exec", 1024)  # 1024 for AST
-        except ValueError:
-            start, end = getstatementrange_old(lineno, source, assertion)
-            return None, start, end
+        astnode = compile(content, "source", "exec", 1024)  # 1024 for AST
+
     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)
 
@@ -373,43 +372,8 @@ def getstatementrange_ast(lineno, source
     # 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,))
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/assertion/__init__.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/assertion/__init__.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/assertion/__init__.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/assertion/__init__.py
@@ -7,43 +7,45 @@ import six
 
 from _pytest.assertion import util
 from _pytest.assertion import rewrite
 from _pytest.assertion import truncate
 
 
 def pytest_addoption(parser):
     group = parser.getgroup("debugconfig")
-    group.addoption('--assert',
-                    action="store",
-                    dest="assertmode",
-                    choices=("rewrite", "plain",),
-                    default="rewrite",
-                    metavar="MODE",
-                    help="""Control assertion debugging tools.  'plain'
+    group.addoption(
+        "--assert",
+        action="store",
+        dest="assertmode",
+        choices=("rewrite", "plain"),
+        default="rewrite",
+        metavar="MODE",
+        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.""")
+                            expression information.""",
+    )
 
 
 def register_assert_rewrite(*names):
     """Register one or more module names 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'
+            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)
@@ -51,96 +53,99 @@ def register_assert_rewrite(*names):
 
 class DummyRewriteHook(object):
     """A no-op import hook for when rewriting is disabled."""
 
     def mark_rewrite(self, *names):
         pass
 
 
-class AssertionState:
+class AssertionState(object):
     """State for the assertion plugin."""
 
     def __init__(self, config, mode):
         self.mode = mode
         self.trace = config.trace.root.get("assertion")
         self.hook = None
 
 
 def install_importhook(config):
     """Try to install the rewrite hook, raise SystemError if it fails."""
     # Jython has an AST bug that make the assertion rewriting hook malfunction.
-    if (sys.platform.startswith('java')):
-        raise SystemError('rewrite not supported')
+    if sys.platform.startswith("java"):
+        raise SystemError("rewrite not supported")
 
-    config._assertstate = AssertionState(config, 'rewrite')
+    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')
+    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)
-    assertstate = getattr(session.config, '_assertstate', None)
+    assertstate = getattr(session.config, "_assertstate", None)
     if assertstate:
         if assertstate.hook is not None:
             assertstate.hook.set_session(session)
 
 
 def pytest_runtest_setup(item):
     """Setup the pytest_assertrepr_compare hook
 
     The newinterpret and rewrite modules will use util._reprcompare if
     it exists to use custom reporting via the
     pytest_assertrepr_compare hook.  This sets up this custom
     comparison for the test.
     """
+
     def callbinrepr(op, left, right):
         """Call the pytest_assertrepr_compare hook and prepare the result
 
         This uses the first result from the hook and then ensures the
         following:
         * Overly verbose explanations are truncated unless configured otherwise
           (eg. if running in verbose mode).
         * Embedded newlines are escaped to help util.format_explanation()
           later.
         * If the rewrite mode is used embedded %-characters are replaced
           to protect later % formatting.
 
         The result can be formatted by util.format_explanation() for
         pretty printing.
         """
         hook_result = item.ihook.pytest_assertrepr_compare(
-            config=item.config, op=op, left=left, right=right)
+            config=item.config, op=op, left=left, right=right
+        )
         for new_expl in hook_result:
             if new_expl:
                 new_expl = truncate.truncate_if_required(new_expl, item)
                 new_expl = [line.replace("\n", "\\n") for line in new_expl]
                 res = six.text_type("\n~").join(new_expl)
                 if item.config.getvalue("assertmode") == "rewrite":
                     res = res.replace("%", "%%")
                 return res
+
     util._reprcompare = callbinrepr
 
 
 def pytest_runtest_teardown(item):
     util._reprcompare = None
 
 
 def pytest_sessionfinish(session):
-    assertstate = getattr(session.config, '_assertstate', None)
+    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
 pytest_assertrepr_compare = util.assertrepr_compare
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/assertion/rewrite.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/assertion/rewrite.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/assertion/rewrite.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/assertion/rewrite.py
@@ -1,24 +1,25 @@
 """Rewrite assertion AST to produce nice error messages"""
 from __future__ import absolute_import, division, print_function
 import ast
-import _ast
 import errno
 import itertools
 import imp
 import marshal
 import os
 import re
 import six
 import struct
 import sys
 import types
 
+import atomicwrites
 import py
+
 from _pytest.assertion import util
 
 
 # pytest caches rewritten pycs in __pycache__.
 if hasattr(imp, "get_tag"):
     PYTEST_TAG = imp.get_tag() + "-PYTEST"
 else:
     if hasattr(sys, "pypy_version_info"):
@@ -34,16 +35,17 @@ else:
 PYC_EXT = ".py" + (__debug__ and "c" or "o")
 PYC_TAIL = "." + PYTEST_TAG + PYC_EXT
 
 ASCII_IS_DEFAULT_ENCODING = sys.version_info[0] < 3
 
 if sys.version_info >= (3, 5):
     ast_Call = ast.Call
 else:
+
     def ast_Call(a, b, c):
         return ast.Call(a, b, c, None, None)
 
 
 class AssertionRewritingHook(object):
     """PEP302 Import hook which rewrites asserts."""
 
     def __init__(self, config):
@@ -136,66 +138,68 @@ 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(self.config, fn_pypath)
             if co is None:
                 # Probably a SyntaxError in the test.
                 return None
             if write:
-                _make_rewritten_pyc(state, source_stat, pyc, co)
+                _write_pyc(state, co, source_stat, pyc)
         else:
             state.trace("found cached rewritten pyc for %r" % (fn,))
         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':
+        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,))
+                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:
             if fn_pypath.fnmatch(pat):
                 state.trace("matched test file %r" % (fn,))
                 return True
 
         for marked in self._must_rewrite:
-            if name == marked or name.startswith(marked + '.'):
+            if name == marked or 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 rewritten.
 
         The named module or package as well as any nested modules will
         be rewritten on import.
         """
-        already_imported = set(names).intersection(set(sys.modules))
-        if already_imported:
-            for name in already_imported:
-                if name not in self._rewritten_names:
-                    self._warn_already_imported(name)
+        already_imported = (
+            set(names).intersection(sys.modules).difference(self._rewritten_names)
+        )
+        for name in already_imported:
+            if not AssertionRewriter.is_rewrite_disabled(
+                sys.modules[name].__doc__ or ""
+            ):
+                self._warn_already_imported(name)
         self._must_rewrite.update(names)
 
     def _warn_already_imported(self, name):
         self.config.warn(
-            'P1',
-            'Module already imported so cannot be rewritten: %s' % name)
+            "P1", "Module already imported so cannot be rewritten: %s" % name
+        )
 
     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,
         # the reload() builtin will not work correctly.)
         if name in sys.modules:
             return sys.modules[name]
 
@@ -229,63 +233,60 @@ class AssertionRewritingHook(object):
     @classmethod
     def _register_with_pkg_resources(cls):
         """
         Ensure package resources can be loaded from this loader. May be called
         multiple times, as the operation is idempotent.
         """
         try:
             import pkg_resources
+
             # access an attribute in case a deferred importer is present
             pkg_resources.__name__
         except ImportError:
             return
 
         # Since pytest tests are always located in the file system, the
         #  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:
+        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
     # (C)Python, since these "pycs" should never be seen by builtin
     # import. However, there's little reason deviate, and I hope
     # sometime to be able to use imp.load_compiled to load them. (See
     # the comment in load_module above.)
     try:
-        fp = open(pyc, "wb")
-    except IOError:
-        err = sys.exc_info()[1].errno
-        state.trace("error writing pyc file at %s: errno=%s" % (pyc, err))
+        with atomicwrites.atomic_write(pyc, mode="wb", overwrite=True) as fp:
+            fp.write(imp.get_magic())
+            mtime = int(source_stat.mtime)
+            size = source_stat.size & 0xFFFFFFFF
+            fp.write(struct.pack("<ll", mtime, size))
+            fp.write(marshal.dumps(co))
+    except EnvironmentError as e:
+        state.trace("error writing pyc file at %s: errno=%s" % (pyc, e.errno))
         # we ignore any failure to write the cache file
         # there are many reasons, permission-denied, __pycache__ being a
         # file etc.
         return False
-    try:
-        fp.write(imp.get_magic())
-        mtime = int(source_stat.mtime)
-        size = source_stat.size & 0xFFFFFFFF
-        fp.write(struct.pack("<ll", mtime, size))
-        marshal.dump(co, fp)
-    finally:
-        fp.close()
     return True
 
 
 RN = "\r\n".encode("utf-8")
 N = "\n".encode("utf-8")
 
 cookie_re = re.compile(r"^[ \t\f]*#.*coding[:=][ \t]*[-\w.]+")
-BOM_UTF8 = '\xef\xbb\xbf'
+BOM_UTF8 = "\xef\xbb\xbf"
 
 
 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")
@@ -300,19 +301,21 @@ def _rewrite_test(config, fn):
         # preserve this error behavior, we could force ast.parse() to use ASCII
         # as the encoding by inserting a coding cookie. Unfortunately, that
         # messes up line numbers. Thus, we have to check ourselves if anything
         # is outside the ASCII range in the case no encoding is explicitly
         # declared. For more context, see issue #269. Yay for Python 3 which
         # gets this right.
         end1 = source.find("\n")
         end2 = source.find("\n", end1 + 1)
-        if (not source.startswith(BOM_UTF8) and
-            cookie_re.match(source[0:end1]) is None and
-                cookie_re.match(source[end1 + 1:end2]) is None):
+        if (
+            not source.startswith(BOM_UTF8)
+            and cookie_re.match(source[0:end1]) is None
+            and cookie_re.match(source[end1 + 1:end2]) is None
+        ):
             if hasattr(state, "_indecode"):
                 # encodings imported us again, so don't rewrite.
                 return None, None
             state._indecode = True
             try:
                 try:
                     source.decode("ascii")
                 except UnicodeDecodeError:
@@ -332,59 +335,48 @@ def _rewrite_test(config, fn):
     except SyntaxError:
         # It's possible that this error is from some bug in the
         # assertion rewriting, but I don't know of a fast way to tell.
         state.trace("failed to compile: %r" % (fn,))
         return None, None
     return stat, co
 
 
-def _make_rewritten_pyc(state, source_stat, pyc, co):
-    """Try to dump rewritten code to *pyc*."""
-    if sys.platform.startswith("win"):
-        # Windows grants exclusive access to open files and doesn't have atomic
-        # rename, so just write into the final file.
-        _write_pyc(state, co, source_stat, pyc)
-    else:
-        # When not on windows, assume rename is atomic. Dump the code object
-        # into a file specific to this process and atomically replace it.
-        proc_pyc = pyc + "." + str(os.getpid())
-        if _write_pyc(state, co, source_stat, proc_pyc):
-            os.rename(proc_pyc, pyc)
-
-
 def _read_pyc(source, pyc, trace=lambda x: None):
     """Possibly read a pytest pyc containing rewritten code.
 
     Return rewritten code if successful or None if not.
     """
     try:
         fp = open(pyc, "rb")
     except IOError:
         return None
     with fp:
         try:
             mtime = int(source.mtime())
             size = source.size()
             data = fp.read(12)
         except EnvironmentError as e:
-            trace('_read_pyc(%s): EnvironmentError %s' % (source, e))
+            trace("_read_pyc(%s): EnvironmentError %s" % (source, e))
             return None
         # Check for invalid or out of date pyc file.
-        if (len(data) != 12 or data[:4] != imp.get_magic() or
-                struct.unpack("<ll", data[4:]) != (mtime, size)):
-            trace('_read_pyc(%s): invalid or out of date pyc' % source)
+        if (
+            len(data) != 12
+            or data[:4] != imp.get_magic()
+            or struct.unpack("<ll", data[4:]) != (mtime, size)
+        ):
+            trace("_read_pyc(%s): invalid or out of date pyc" % source)
             return None
         try:
             co = marshal.load(fp)
         except Exception as e:
-            trace('_read_pyc(%s): marshal.load error %s' % (source, e))
+            trace("_read_pyc(%s): marshal.load error %s" % (source, e))
             return None
         if not isinstance(co, types.CodeType):
-            trace('_read_pyc(%s): not a code object' % source)
+            trace("_read_pyc(%s): not a code object" % source)
             return None
         return co
 
 
 def rewrite_asserts(mod, module_path=None, config=None):
     """Rewrite the assert statements in mod."""
     AssertionRewriter(module_path, config).run(mod)
 
@@ -444,17 +436,17 @@ def _should_repr_global_name(obj):
 
 
 def _format_boolop(explanations, is_or):
     explanation = "(" + (is_or and " or " or " and ").join(explanations) + ")"
     if isinstance(explanation, six.text_type):
         t = six.text_type
     else:
         t = six.binary_type
-    return explanation.replace(t('%'), t('%%'))
+    return explanation.replace(t("%"), t("%%"))
 
 
 def _call_reprcompare(ops, results, expls, each_obj):
     for i, res, expl in zip(range(len(ops)), results, expls):
         try:
             done = not res
         except Exception:
             done = True
@@ -462,22 +454,17 @@ def _call_reprcompare(ops, results, expl
             break
     if util._reprcompare is not None:
         custom = util._reprcompare(ops[i], each_obj[i], each_obj[i + 1])
         if custom is not None:
             return custom
     return expl
 
 
-unary_map = {
-    ast.Not: "not %s",
-    ast.Invert: "~%s",
-    ast.USub: "-%s",
-    ast.UAdd: "+%s"
-}
+unary_map = {ast.Not: "not %s", ast.Invert: "~%s", ast.USub: "-%s", ast.UAdd: "+%s"}
 
 binop_map = {
     ast.BitOr: "|",
     ast.BitXor: "^",
     ast.BitAnd: "&",
     ast.LShift: "<<",
     ast.RShift: ">>",
     ast.Add: "+",
@@ -491,41 +478,44 @@ binop_map = {
     ast.Lt: "<",
     ast.LtE: "<=",
     ast.Gt: ">",
     ast.GtE: ">=",
     ast.Pow: "**",
     ast.Is: "is",
     ast.IsNot: "is not",
     ast.In: "in",
-    ast.NotIn: "not 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"):
     _NameConstant = ast.NameConstant
 else:
+
     def _NameConstant(c):
         return ast.Name(str(c), ast.Load())
 
 
 def set_location(node, lineno, col_offset):
     """Set node location information recursively."""
+
     def _fix(node, lineno, col_offset):
         if "lineno" in node._attributes:
             node.lineno = lineno
         if "col_offset" in node._attributes:
             node.col_offset = col_offset
         for child in ast.iter_child_nodes(node):
             _fix(child, lineno, col_offset)
+
     _fix(node, lineno, col_offset)
     return node
 
 
 class AssertionRewriter(ast.NodeVisitor):
     """Assertion rewriting implementation.
 
     The main entrypoint is to call .run() with an ast.Module instance,
@@ -584,40 +574,49 @@ class AssertionRewriter(ast.NodeVisitor)
 
     def run(self, mod):
         """Find all assert statements in *mod* and rewrite them."""
         if not mod.body:
             # Nothing to do.
             return
         # Insert some special imports at the top of the module but after any
         # docstrings and __future__ imports.
-        aliases = [ast.alias(py.builtin.builtins.__name__, "@py_builtins"),
-                   ast.alias("_pytest.assertion.rewrite", "@pytest_ar")]
+        aliases = [
+            ast.alias(py.builtin.builtins.__name__, "@py_builtins"),
+            ast.alias("_pytest.assertion.rewrite", "@pytest_ar"),
+        ]
         doc = getattr(mod, "docstring", None)
         expect_docstring = doc is None
         if doc is not None and self.is_rewrite_disabled(doc):
             return
         pos = 0
         lineno = 1
         for item in mod.body:
-            if (expect_docstring and isinstance(item, ast.Expr) and
-                    isinstance(item.value, ast.Str)):
+            if (
+                expect_docstring
+                and isinstance(item, ast.Expr)
+                and isinstance(item.value, ast.Str)
+            ):
                 doc = item.value.s
                 if self.is_rewrite_disabled(doc):
                     return
                 expect_docstring = False
-            elif (not isinstance(item, ast.ImportFrom) or item.level > 0 or
-                  item.module != "__future__"):
+            elif (
+                not isinstance(item, ast.ImportFrom)
+                or item.level > 0
+                or item.module != "__future__"
+            ):
                 lineno = item.lineno
                 break
             pos += 1
         else:
             lineno = item.lineno
-        imports = [ast.Import([alias], lineno=lineno, col_offset=0)
-                   for alias in aliases]
+        imports = [
+            ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases
+        ]
         mod.body[pos:pos] = imports
         # Collect asserts.
         nodes = [mod]
         while nodes:
             node = nodes.pop()
             for name, field in ast.iter_fields(node):
                 if isinstance(field, list):
                     new = []
@@ -625,23 +624,27 @@ class AssertionRewriter(ast.NodeVisitor)
                         if isinstance(child, ast.Assert):
                             # Transform assert.
                             new.extend(self.visit(child))
                         else:
                             new.append(child)
                             if isinstance(child, ast.AST):
                                 nodes.append(child)
                     setattr(node, name, new)
-                elif (isinstance(field, ast.AST) and
-                      # Don't recurse into expressions as they can't contain
-                      # asserts.
-                      not isinstance(field, ast.expr)):
+                elif (
+                    isinstance(field, ast.AST)
+                    and
+                    # Don't recurse into expressions as they can't contain
+                    # asserts.
+                    not isinstance(field, ast.expr)
+                ):
                     nodes.append(field)
 
-    def is_rewrite_disabled(self, docstring):
+    @staticmethod
+    def is_rewrite_disabled(docstring):
         return "PYTEST_DONT_REWRITE" in docstring
 
     def variable(self):
         """Get a new variable."""
         # Use a character invalid in python identifiers to avoid clashing.
         name = "@py_assert" + str(next(self.variable_counter))
         self.variables.append(name)
         return name
@@ -725,50 +728,52 @@ class AssertionRewriter(ast.NodeVisitor)
         This rewrites the test of an assertion to provide
         intermediate values and replace it with an if statement which
         raises an assertion error with a detailed explanation in case
         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.config.warn(
+                "R1",
+                "assertion is always true, perhaps " "remove parentheses?",
+                fslocation=fslocation,
+            )
         self.statements = []
         self.variables = []
         self.variable_counter = itertools.count()
         self.stack = []
         self.on_failure = []
         self.push_format_context()
         # Rewrite assert into a bunch of statements.
         top_condition, explanation = self.visit(assert_.test)
         # Create failure message.
         body = self.on_failure
         negation = ast.UnaryOp(ast.Not(), top_condition)
         self.statements.append(ast.If(negation, body, []))
         if assert_.msg:
-            assertmsg = self.helper('format_assertmsg', assert_.msg)
+            assertmsg = self.helper("format_assertmsg", assert_.msg)
             explanation = "\n>assert " + explanation
         else:
             assertmsg = ast.Str("")
             explanation = "assert " + explanation
         template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation))
         msg = self.pop_format_context(template)
         fmt = self.helper("format_explanation", msg)
         err_name = ast.Name("AssertionError", ast.Load())
         exc = ast_Call(err_name, [fmt], [])
         if sys.version_info[0] >= 3:
             raise_ = ast.Raise(exc, None)
         else:
             raise_ = ast.Raise(exc, None, None)
         body.append(raise_)
         # Clear temporary variables by setting them to None.
         if self.variables:
-            variables = [ast.Name(name, ast.Store())
-                         for name in self.variables]
+            variables = [ast.Name(name, ast.Store()) for name in self.variables]
             clear = ast.Assign(variables, _NameConstant(None))
             self.statements.append(clear)
         # Fix line numbers.
         for stmt in self.statements:
             set_location(stmt, assert_.lineno, assert_.col_offset)
         return self.statements
 
     def visit_Name(self, name):
@@ -845,27 +850,27 @@ class AssertionRewriter(ast.NodeVisitor)
         for keyword in call.keywords:
             res, expl = self.visit(keyword.value)
             new_kwargs.append(ast.keyword(keyword.arg, res))
             if keyword.arg:
                 arg_expls.append(keyword.arg + "=" + expl)
             else:  # **args have `arg` keywords with an .arg of None
                 arg_expls.append("**" + expl)
 
-        expl = "%s(%s)" % (func_expl, ', '.join(arg_expls))
+        expl = "%s(%s)" % (func_expl, ", ".join(arg_expls))
         new_call = ast.Call(new_func, new_args, new_kwargs)
         res = self.assign(new_call)
         res_expl = self.explanation_param(self.display(res))
         outer_expl = "%s\n{%s = %s\n}" % (res_expl, res_expl, expl)
         return res, outer_expl
 
     def visit_Starred(self, starred):
         # From Python 3.5, a Starred node can appear in a function call
         res, expl = self.visit(starred.value)
-        return starred, '*' + expl
+        return starred, "*" + expl
 
     def visit_Call_legacy(self, call):
         """
         visit `ast.Call nodes on 3.4 and below`
         """
         new_func, func_expl = self.visit(call.func)
         arg_expls = []
         new_args = []
@@ -880,19 +885,18 @@ class AssertionRewriter(ast.NodeVisitor)
             new_kwargs.append(ast.keyword(keyword.arg, res))
             arg_expls.append(keyword.arg + "=" + expl)
         if call.starargs:
             new_star, expl = self.visit(call.starargs)
             arg_expls.append("*" + expl)
         if call.kwargs:
             new_kwarg, expl = self.visit(call.kwargs)
             arg_expls.append("**" + expl)
-        expl = "%s(%s)" % (func_expl, ', '.join(arg_expls))
-        new_call = ast.Call(new_func, new_args, new_kwargs,
-                            new_star, new_kwarg)
+        expl = "%s(%s)" % (func_expl, ", ".join(arg_expls))
+        new_call = ast.Call(new_func, new_args, new_kwargs, new_star, new_kwarg)
         res = self.assign(new_call)
         res_expl = self.explanation_param(self.display(res))
         outer_expl = "%s\n{%s = %s\n}" % (res_expl, res_expl, expl)
         return res, outer_expl
 
     # ast.Call signature changed on 3.5,
     # conditionally change  which methods is named
     # visit_Call depending on Python version
@@ -909,40 +913,42 @@ class AssertionRewriter(ast.NodeVisitor)
         res_expl = self.explanation_param(self.display(res))
         pat = "%s\n{%s = %s.%s\n}"
         expl = pat % (res_expl, res_expl, value_expl, attr.attr)
         return res, expl
 
     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)
+        if isinstance(comp.left, (ast.Compare, ast.BoolOp)):
+            left_expl = "({})".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]
         it = zip(range(len(comp.ops)), comp.ops, comp.comparators)
         expls = []
         syms = []
         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)
+            if isinstance(next_operand, (ast.Compare, ast.BoolOp)):
+                next_expl = "({})".format(next_expl)
             results.append(next_res)
             sym = binop_map[op.__class__]
             syms.append(ast.Str(sym))
             expl = "%s %s %s" % (left_expl, sym, next_expl)
             expls.append(ast.Str(expl))
             res_expr = ast.Compare(left_res, [op], [next_res])
             self.statements.append(ast.Assign([store_names[i]], res_expr))
             left_res, left_expl = next_res, next_expl
         # Use pytest.assertion.util._reprcompare if that's available.
-        expl_call = self.helper("call_reprcompare",
-                                ast.Tuple(syms, ast.Load()),
-                                ast.Tuple(load_names, ast.Load()),
-                                ast.Tuple(expls, ast.Load()),
-                                ast.Tuple(results, ast.Load()))
+        expl_call = self.helper(
+            "call_reprcompare",
+            ast.Tuple(syms, ast.Load()),
+            ast.Tuple(load_names, ast.Load()),
+            ast.Tuple(expls, ast.Load()),
+            ast.Tuple(results, ast.Load()),
+        )
         if len(comp.ops) > 1:
             res = ast.BoolOp(ast.And(), load_names)
         else:
             res = load_names[0]
         return res, self.explanation_param(self.pop_format_context(expl_call))
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/assertion/truncate.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/assertion/truncate.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/assertion/truncate.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/assertion/truncate.py
@@ -29,17 +29,17 @@ def _should_truncate_item(item):
     Whether or not this test item is eligible for truncation.
     """
     verbose = item.config.option.verbose
     return verbose < 2 and not _running_on_ci()
 
 
 def _running_on_ci():
     """Check if we're currently running on a CI system."""
-    env_vars = ['CI', 'BUILD_NUMBER']
+    env_vars = ["CI", "BUILD_NUMBER"]
     return any(var in os.environ for var in env_vars)
 
 
 def _truncate_explanation(input_lines, max_lines=None, max_chars=None):
     """
     Truncate given list of strings that makes up the assertion explanation.
 
     Truncates to either 8 lines, or 640 characters - whichever the input reaches
@@ -62,26 +62,23 @@ def _truncate_explanation(input_lines, m
     truncated_explanation = _truncate_by_char_count(truncated_explanation, max_chars)
 
     # Add ellipsis to final line
     truncated_explanation[-1] = truncated_explanation[-1] + "..."
 
     # Append useful message to explanation
     truncated_line_count = len(input_lines) - len(truncated_explanation)
     truncated_line_count += 1  # Account for the part-truncated final line
-    msg = '...Full output truncated'
+    msg = "...Full output truncated"
     if truncated_line_count == 1:
-        msg += ' ({0} line hidden)'.format(truncated_line_count)
+        msg += " ({} line hidden)".format(truncated_line_count)
     else:
-        msg += ' ({0} lines hidden)'.format(truncated_line_count)
-    msg += ", {0}" .format(USAGE_MSG)
-    truncated_explanation.extend([
-        six.text_type(""),
-        six.text_type(msg),
-    ])
+        msg += " ({} lines hidden)".format(truncated_line_count)
+    msg += ", {}".format(USAGE_MSG)
+    truncated_explanation.extend([six.text_type(""), six.text_type(msg)])
     return truncated_explanation
 
 
 def _truncate_by_char_count(input_lines, max_chars):
     # Check if truncation required
     if len("".join(input_lines)) <= max_chars:
         return input_lines
 
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/assertion/util.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/assertion/util.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/assertion/util.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/assertion/util.py
@@ -1,35 +1,31 @@
 """Utilities for assertion debugging"""
 from __future__ import absolute_import, division, print_function
 import pprint
 
 import _pytest._code
 import py
 import six
-try:
-    from collections import Sequence
-except ImportError:
-    Sequence = list
-
+from ..compat import Sequence
 
 u = six.text_type
 
 # The _reprcompare attribute on the util module is used by the new assertion
 # interpretation code and assertion rewriter to detect this plugin was
 # loaded and in turn call the hooks defined here as part of the
 # DebugInterpreter.
 _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')
+        return u(s, "utf-8", "replace")
     except TypeError:
         return s
 
 
 def format_explanation(explanation):
     """This formats an explanation
 
     Normally all embedded newlines are escaped, however there are
@@ -37,67 +33,67 @@ def format_explanation(explanation):
     cover nested explanations, see function and attribute explanations
     for examples (.visit_Call(), visit_Attribute()).  The last one is
     for when one explanation needs to span multiple lines, e.g. when
     displaying diffs.
     """
     explanation = ecu(explanation)
     lines = _split_explanation(explanation)
     result = _format_lines(lines)
-    return u('\n').join(result)
+    return u("\n").join(result)
 
 
 def _split_explanation(explanation):
     """Return a list of individual lines in the explanation
 
     This will return a list of lines split on '\n{', '\n}' and '\n~'.
     Any other newlines will be escaped and appear in the line as the
     literal '\n' characters.
     """
-    raw_lines = (explanation or u('')).split('\n')
+    raw_lines = (explanation or u("")).split("\n")
     lines = [raw_lines[0]]
     for values in raw_lines[1:]:
-        if values and values[0] in ['{', '}', '~', '>']:
+        if values and values[0] in ["{", "}", "~", ">"]:
             lines.append(values)
         else:
-            lines[-1] += '\\n' + values
+            lines[-1] += "\\n" + values
     return lines
 
 
 def _format_lines(lines):
     """Format the individual lines
 
     This will replace the '{', '}' and '~' characters of our mini
     formatting language with the proper 'where ...', 'and ...' and ' +
     ...' text, taking care of indentation along the way.
 
     Return a list of formatted lines.
     """
     result = lines[:1]
     stack = [0]
     stackcnt = [0]
     for line in lines[1:]:
-        if line.startswith('{'):
+        if line.startswith("{"):
             if stackcnt[-1]:
-                s = u('and   ')
+                s = u("and   ")
             else:
-                s = u('where ')
+                s = u("where ")
             stack.append(len(result))
             stackcnt[-1] += 1
             stackcnt.append(0)
-            result.append(u(' +') + u('  ') * (len(stack) - 1) + s + line[1:])
-        elif line.startswith('}'):
+            result.append(u(" +") + u("  ") * (len(stack) - 1) + s + line[1:])
+        elif line.startswith("}"):
             stack.pop()
             stackcnt.pop()
             result[stack[-1]] += line[1:]
         else:
-            assert line[0] in ['~', '>']
+            assert line[0] in ["~", ">"]
             stack[-1] += 1
-            indent = len(stack) if line.startswith('~') else len(stack) - 1
-            result.append(u('  ') * indent + line[1:])
+            indent = len(stack) if line.startswith("~") else len(stack) - 1
+            result.append(u("  ") * indent + line[1:])
     assert len(stack) == 1
     return result
 
 
 # Provide basestring in python3
 try:
     basestring = basestring
 except NameError:
@@ -105,20 +101,20 @@ except NameError:
 
 
 def assertrepr_compare(config, op, left, right):
     """Return specialised explanations for some operators/operands"""
     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') % (ecu(left_repr), op, ecu(right_repr))
+    summary = u("%s %s %s") % (ecu(left_repr), op, ecu(right_repr))
 
     def issequence(x):
-        return (isinstance(x, (list, tuple, Sequence)) and not isinstance(x, basestring))
+        return isinstance(x, Sequence) and not isinstance(x, basestring)
 
     def istext(x):
         return isinstance(x, basestring)
 
     def isdict(x):
         return isinstance(x, dict)
 
     def isset(x):
@@ -126,183 +122,217 @@ def assertrepr_compare(config, op, left,
 
     def isiterable(obj):
         try:
             iter(obj)
             return not istext(obj)
         except TypeError:
             return False
 
-    verbose = config.getoption('verbose')
+    verbose = config.getoption("verbose")
     explanation = None
     try:
-        if op == '==':
+        if op == "==":
             if istext(left) and istext(right):
                 explanation = _diff_text(left, right, verbose)
             else:
                 if issequence(left) and issequence(right):
                     explanation = _compare_eq_sequence(left, right, verbose)
                 elif isset(left) and isset(right):
                     explanation = _compare_eq_set(left, right, verbose)
                 elif isdict(left) and isdict(right):
                     explanation = _compare_eq_dict(left, right, verbose)
                 if isiterable(left) and isiterable(right):
                     expl = _compare_eq_iterable(left, right, verbose)
                     if explanation is not None:
                         explanation.extend(expl)
                     else:
                         explanation = expl
-        elif op == 'not in':
+        elif op == "not in":
             if istext(left) and istext(right):
                 explanation = _notin_text(left, right, verbose)
     except Exception:
         explanation = [
-            u('(pytest_assertion plugin: representation of details failed.  '
-              'Probably an object has a faulty __repr__.)'),
-            u(_pytest._code.ExceptionInfo())]
+            u(
+                "(pytest_assertion plugin: representation of details failed.  "
+                "Probably an object has a faulty __repr__.)"
+            ),
+            u(_pytest._code.ExceptionInfo()),
+        ]
 
     if not explanation:
         return None
 
     return [summary] + explanation
 
 
 def _diff_text(left, right, verbose=False):
     """Return the explanation for the diff between text or bytes
 
     Unless --verbose is used this will skip leading and trailing
     characters which are identical to keep the diff minimal.
 
     If the input are bytes they will be safely converted to text.
     """
     from difflib import ndiff
+
     explanation = []
+
+    def escape_for_readable_diff(binary_text):
+        """
+        Ensures that the internal string is always valid unicode, converting any bytes safely to valid unicode.
+        This is done using repr() which then needs post-processing to fix the encompassing quotes and un-escape
+        newlines and carriage returns (#429).
+        """
+        r = six.text_type(repr(binary_text)[1:-1])
+        r = r.replace(r"\n", "\n")
+        r = r.replace(r"\r", "\r")
+        return r
+
     if isinstance(left, six.binary_type):
-        left = u(repr(left)[1:-1]).replace(r'\n', '\n')
+        left = escape_for_readable_diff(left)
     if isinstance(right, six.binary_type):
-        right = u(repr(right)[1:-1]).replace(r'\n', '\n')
+        right = escape_for_readable_diff(right)
     if not verbose:
         i = 0  # just in case left or right has zero length
         for i in range(min(len(left), len(right))):
             if left[i] != right[i]:
                 break
         if i > 42:
-            i -= 10                 # Provide some context
-            explanation = [u('Skipping %s identical leading '
-                             'characters in diff, use -v to show') % i]
+            i -= 10  # Provide some context
+            explanation = [
+                u("Skipping %s identical leading " "characters in diff, use -v to show")
+                % i
+            ]
             left = left[i:]
             right = right[i:]
         if len(left) == len(right):
             for i in range(len(left)):
                 if left[-i] != right[-i]:
                     break
             if i > 42:
-                i -= 10     # Provide some context
-                explanation += [u('Skipping %s identical trailing '
-                                  'characters in diff, use -v to show') % i]
+                i -= 10  # Provide some context
+                explanation += [
+                    u(
+                        "Skipping %s identical trailing "
+                        "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(keepends),
-                                      right.splitlines(keepends))]
+    if left.isspace() or right.isspace():
+        left = repr(str(left))
+        right = repr(str(right))
+        explanation += [u"Strings contain only whitespace, escaping them using repr()"]
+    explanation += [
+        line.strip("\n")
+        for line in ndiff(left.splitlines(keepends), right.splitlines(keepends))
+    ]
     return explanation
 
 
 def _compare_eq_iterable(left, right, verbose=False):
     if not verbose:
-        return [u('Use -v to get the full diff')]
+        return [u("Use -v to get the full diff")]
     # dynamic import to speedup pytest
     import difflib
 
     try:
         left_formatting = pprint.pformat(left).splitlines()
         right_formatting = pprint.pformat(right).splitlines()
-        explanation = [u('Full diff:')]
+        explanation = [u("Full diff:")]
     except Exception:
         # hack: PrettyPrinter.pformat() in python 2 fails when formatting items that can't be sorted(), ie, calling
         # sorted() on a list would raise. See issue #718.
         # As a workaround, the full diff is generated by using the repr() string of each item of each container.
         left_formatting = sorted(repr(x) for x in left)
         right_formatting = sorted(repr(x) for x in right)
-        explanation = [u('Full diff (fallback to calling repr on each item):')]
-    explanation.extend(line.strip() for line in difflib.ndiff(left_formatting, right_formatting))
+        explanation = [u("Full diff (fallback to calling repr on each item):")]
+    explanation.extend(
+        line.strip() for line in difflib.ndiff(left_formatting, right_formatting)
+    )
     return explanation
 
 
 def _compare_eq_sequence(left, right, verbose=False):
     explanation = []
     for i in range(min(len(left), len(right))):
         if left[i] != right[i]:
-            explanation += [u('At index %s diff: %r != %r')
-                            % (i, left[i], right[i])]
+            explanation += [u("At index %s diff: %r != %r") % (i, left[i], right[i])]
             break
     if len(left) > len(right):
-        explanation += [u('Left contains more items, first extra item: %s')
-                        % py.io.saferepr(left[len(right)],)]
+        explanation += [
+            u("Left contains more items, first extra item: %s")
+            % py.io.saferepr(left[len(right)])
+        ]
     elif len(left) < len(right):
         explanation += [
-            u('Right contains more items, first extra item: %s') %
-            py.io.saferepr(right[len(left)],)]
+            u("Right contains more items, first extra item: %s")
+            % py.io.saferepr(right[len(left)])
+        ]
     return explanation
 
 
 def _compare_eq_set(left, right, verbose=False):
     explanation = []
     diff_left = left - right
     diff_right = right - left
     if diff_left:
-        explanation.append(u('Extra items in the left set:'))
+        explanation.append(u("Extra items in the left set:"))
         for item in diff_left:
             explanation.append(py.io.saferepr(item))
     if diff_right:
-        explanation.append(u('Extra items in the right set:'))
+        explanation.append(u("Extra items in the right set:"))
         for item in diff_right:
             explanation.append(py.io.saferepr(item))
     return explanation
 
 
 def _compare_eq_dict(left, right, verbose=False):
     explanation = []
     common = set(left).intersection(set(right))
-    same = dict((k, left[k]) for k in common if left[k] == right[k])
+    same = {k: left[k] for k in common if left[k] == right[k]}
     if same and verbose < 2:
-        explanation += [u('Omitting %s identical items, use -vv to show') %
-                        len(same)]
+        explanation += [u("Omitting %s identical items, use -vv to show") % len(same)]
     elif same:
-        explanation += [u('Common items:')]
+        explanation += [u("Common items:")]
         explanation += pprint.pformat(same).splitlines()
-    diff = set(k for k in common if left[k] != right[k])
+    diff = {k for k in common if left[k] != right[k]}
     if diff:
-        explanation += [u('Differing items:')]
+        explanation += [u("Differing items:")]
         for k in diff:
-            explanation += [py.io.saferepr({k: left[k]}) + ' != ' +
-                            py.io.saferepr({k: right[k]})]
+            explanation += [
+                py.io.saferepr({k: left[k]}) + " != " + py.io.saferepr({k: right[k]})
+            ]
     extra_left = set(left) - set(right)
     if extra_left:
-        explanation.append(u('Left contains more items:'))
-        explanation.extend(pprint.pformat(
-            dict((k, left[k]) for k in extra_left)).splitlines())
+        explanation.append(u("Left contains more items:"))
+        explanation.extend(
+            pprint.pformat({k: left[k] for k in extra_left}).splitlines()
+        )
     extra_right = set(right) - set(left)
     if extra_right:
-        explanation.append(u('Right contains more items:'))
-        explanation.extend(pprint.pformat(
-            dict((k, right[k]) for k in extra_right)).splitlines())
+        explanation.append(u("Right contains more items:"))
+        explanation.extend(
+            pprint.pformat({k: right[k] for k in extra_right}).splitlines()
+        )
     return explanation
 
 
 def _notin_text(term, text, verbose=False):
     index = text.find(term)
     head = text[:index]
     tail = text[index + len(term):]
     correct_text = head + tail
     diff = _diff_text(correct_text, text, verbose)
-    newdiff = [u('%s is contained here:') % py.io.saferepr(term, maxsize=42)]
+    newdiff = [u("%s is contained here:") % py.io.saferepr(term, maxsize=42)]
     for line in diff:
-        if line.startswith(u('Skipping')):
+        if line.startswith(u("Skipping")):
             continue
-        if line.startswith(u('- ')):
+        if line.startswith(u("- ")):
             continue
-        if line.startswith(u('+ ')):
-            newdiff.append(u('  ') + line[2:])
+        if line.startswith(u("+ ")):
+            newdiff.append(u("  ") + line[2:])
         else:
             newdiff.append(line)
     return newdiff
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/cacheprovider.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/cacheprovider.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/cacheprovider.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/cacheprovider.py
@@ -1,28 +1,34 @@
 """
 merged implementation of the cache provider
 
 the name cache was not chosen to ensure pluggy automatically
 ignores the external pytest-cache
 """
 from __future__ import absolute_import, division, print_function
+
+from collections import OrderedDict
+
 import py
+import six
+
 import pytest
 import json
 import os
 from os.path import sep as _sep, altsep as _altsep
 
 
 class Cache(object):
+
     def __init__(self, config):
         self.config = config
         self._cachedir = Cache.cache_dir_from_config(config)
         self.trace = config.trace.root.get("cache")
-        if config.getvalue("cacheclear"):
+        if config.getoption("cacheclear"):
             self.trace("clearing cachedir")
             if self._cachedir.check():
                 self._cachedir.remove()
             self._cachedir.mkdir()
 
     @staticmethod
     def cache_dir_from_config(config):
         cache_dir = config.getini("cache_dir")
@@ -43,17 +49,17 @@ class Cache(object):
              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('/'))
+        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.
@@ -79,131 +85,205 @@ class Cache(object):
                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,)
+                code="I9", message="could not create cache path %s" % (path,)
             )
             return
         try:
-            f = path.open('w')
+            f = path.open("w")
         except py.error.ENOTDIR:
             self.config.warn(
-                code='I9', message='cache could not write path %s' % (path,))
+                code="I9", message="cache could not write path %s" % (path,)
+            )
         else:
             with f:
-                self.trace("cache-write %s: %r" % (key, value,))
+                self.trace("cache-write %s: %r" % (key, value))
                 json.dump(value, f, indent=2, sort_keys=True)
 
 
-class LFPlugin:
+class LFPlugin(object):
     """ 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)
+        active_keys = "lf", "failedfirst"
+        self.active = any(config.getoption(key) for key in active_keys)
         self.lastfailed = config.cache.get("cache/lastfailed", {})
         self._previously_failed_count = None
+        self._no_failures_behavior = self.config.getoption("last_failed_no_failures")
 
     def pytest_report_collectionfinish(self):
         if self.active:
             if not self._previously_failed_count:
-                mode = "run all (no recorded failures)"
+                mode = "run {} (no recorded failures)".format(
+                    self._no_failures_behavior
+                )
             else:
-                noun = 'failure' if self._previously_failed_count == 1 else 'failures'
-                suffix = " first" if self.config.getvalue("failedfirst") else ""
+                noun = "failure" if self._previously_failed_count == 1 else "failures"
+                suffix = " first" if self.config.getoption("failedfirst") else ""
                 mode = "rerun previous {count} {noun}{suffix}".format(
                     count=self._previously_failed_count, suffix=suffix, noun=noun
                 )
             return "run-last-failure: %s" % mode
 
     def pytest_runtest_logreport(self, report):
-        if (report.when == 'call' and report.passed) or report.skipped:
+        if (report.when == "call" and report.passed) or report.skipped:
             self.lastfailed.pop(report.nodeid, None)
         elif report.failed:
             self.lastfailed[report.nodeid] = True
 
     def pytest_collectreport(self, report):
-        passed = report.outcome in ('passed', 'skipped')
+        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)
+                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)
+        if self.active:
+            if 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)
+                self._previously_failed_count = len(previously_failed)
+                if not previously_failed:
+                    # running a subset of all tests with recorded failures outside
+                    # of the set of tests currently executing
+                    return
+                if self.config.getoption("lf"):
+                    items[:] = previously_failed
+                    config.hook.pytest_deselected(items=previously_passed)
                 else:
-                    previously_passed.append(item)
-            self._previously_failed_count = len(previously_failed)
-            if not previously_failed:
-                # running a subset of all tests with recorded failures outside
-                # of the set of tests currently executing
-                return
-            if self.config.getvalue("lf"):
-                items[:] = previously_failed
-                config.hook.pytest_deselected(items=previously_passed)
-            else:
-                items[:] = previously_failed + previously_passed
+                    items[:] = previously_failed + previously_passed
+            elif self._no_failures_behavior == "none":
+                config.hook.pytest_deselected(items=items)
+                items[:] = []
 
     def pytest_sessionfinish(self, session):
         config = self.config
-        if config.getvalue("cacheshow") or hasattr(config, "slaveinput"):
+        if config.getoption("cacheshow") or hasattr(config, "slaveinput"):
             return
 
         saved_lastfailed = config.cache.get("cache/lastfailed", {})
         if saved_lastfailed != self.lastfailed:
             config.cache.set("cache/lastfailed", self.lastfailed)
 
 
+class NFPlugin(object):
+    """ Plugin which implements the --nf (run new-first) option """
+
+    def __init__(self, config):
+        self.config = config
+        self.active = config.option.newfirst
+        self.cached_nodeids = config.cache.get("cache/nodeids", [])
+
+    def pytest_collection_modifyitems(self, session, config, items):
+        if self.active:
+            new_items = OrderedDict()
+            other_items = OrderedDict()
+            for item in items:
+                if item.nodeid not in self.cached_nodeids:
+                    new_items[item.nodeid] = item
+                else:
+                    other_items[item.nodeid] = item
+
+            items[:] = self._get_increasing_order(
+                six.itervalues(new_items)
+            ) + self._get_increasing_order(
+                six.itervalues(other_items)
+            )
+        self.cached_nodeids = [x.nodeid for x in items if isinstance(x, pytest.Item)]
+
+    def _get_increasing_order(self, items):
+        return sorted(items, key=lambda item: item.fspath.mtime(), reverse=True)
+
+    def pytest_sessionfinish(self, session):
+        config = self.config
+        if config.getoption("cacheshow") or hasattr(config, "slaveinput"):
+            return
+
+        config.cache.set("cache/nodeids", self.cached_nodeids)
+
+
 def pytest_addoption(parser):
     group = parser.getgroup("general")
     group.addoption(
-        '--lf', '--last-failed', action='store_true', dest="lf",
+        "--lf",
+        "--last-failed",
+        action="store_true",
+        dest="lf",
         help="rerun only the tests that failed "
-             "at the last run (or all if none failed)")
+        "at the last run (or all if none failed)",
+    )
     group.addoption(
-        '--ff', '--failed-first', action='store_true', dest="failedfirst",
+        "--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")
+        "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")
+        "--nf",
+        "--new-first",
+        action="store_true",
+        dest="newfirst",
+        help="run tests from new files first, then the rest of the tests "
+        "sorted by file mtime",
+    )
+    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.")
-    parser.addini(
-        "cache_dir", default='.cache',
-        help="cache directory path.")
+        "--cache-clear",
+        action="store_true",
+        dest="cacheclear",
+        help="remove all cache contents at start of test run.",
+    )
+    parser.addini("cache_dir", default=".pytest_cache", help="cache directory path.")
+    group.addoption(
+        "--lfnf",
+        "--last-failed-no-failures",
+        action="store",
+        dest="last_failed_no_failures",
+        choices=("all", "none"),
+        default="all",
+        help="change the behavior when no test failed in the last run or no "
+        "information about the last failures was found in the cache",
+    )
 
 
 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")
+    config.pluginmanager.register(NFPlugin(config), "nfplugin")
 
 
 @pytest.fixture
 def cache(request):
     """
     Return a cache object that can persist state between testing sessions.
 
     cache.get(key, default)
@@ -220,41 +300,40 @@ def cache(request):
 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 sorted(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)
+            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 sorted(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()))
+                tw.line("%s is a file of length %d" % (key, p.size()))
     return 0
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/capture.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/capture.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/capture.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/capture.py
@@ -12,29 +12,36 @@ import io
 from io import UnsupportedOperation
 from tempfile import TemporaryFile
 
 import six
 import pytest
 from _pytest.compat import CaptureIO
 
 
-patchsysdict = {0: 'stdin', 1: 'stdout', 2: 'stderr'}
+patchsysdict = {0: "stdin", 1: "stdout", 2: "stderr"}
 
 
 def pytest_addoption(parser):
     group = parser.getgroup("general")
     group._addoption(
-        '--capture', action="store",
+        "--capture",
+        action="store",
         default="fd" if hasattr(os, "dup") else "sys",
-        metavar="method", choices=['fd', 'sys', 'no'],
-        help="per-test capturing method: one of fd|sys|no.")
+        metavar="method",
+        choices=["fd", "sys", "no"],
+        help="per-test capturing method: one of fd|sys|no.",
+    )
     group._addoption(
-        '-s', action="store_const", const="no", dest="capture",
-        help="shortcut for --capture=no.")
+        "-s",
+        action="store_const",
+        const="no",
+        dest="capture",
+        help="shortcut for --capture=no.",
+    )
 
 
 @pytest.hookimpl(hookwrapper=True)
 def pytest_load_initial_conftests(early_config, parser, args):
     ns = early_config.known_args_namespace
     if ns.capture == "fd":
         _py36_windowsconsoleio_workaround(sys.stdout)
     _colorama_workaround()
@@ -45,28 +52,29 @@ def pytest_load_initial_conftests(early_
 
     # make sure that capturemanager is properly reset at final shutdown
     early_config.add_cleanup(capman.stop_global_capturing)
 
     # 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
+
     early_config.add_cleanup(silence_logging_at_shutdown)
 
     # finally trigger conftest loading but while capturing (issue93)
     capman.start_global_capturing()
     outcome = yield
     out, err = capman.suspend_global_capture()
     if outcome.excinfo is not None:
         sys.stdout.write(out)
         sys.stderr.write(err)
 
 
-class CaptureManager:
+class CaptureManager(object):
     """
     Capture plugin, manages that the appropriate capture method is enabled/disabled during collection and each
     test phase (setup, call, teardown). After each of those points, the captured output is obtained and
     attached to the collection/runtest report.
 
     There are two levels of capture:
     * global: which is enabled by default and can be suppressed by the ``-s`` option. This is always enabled/disabled
       during collection and each test phase.
@@ -175,143 +183,156 @@ class CaptureManager:
         self.stop_global_capturing()
 
     def suspend_capture_item(self, item, when, in_=False):
         out, err = self.suspend_global_capture(item, in_=in_)
         item.add_report_section(when, "stdout", out)
         item.add_report_section(when, "stderr", err)
 
 
-capture_fixtures = {'capfd', 'capfdbinary', 'capsys', 'capsysbinary'}
+capture_fixtures = {"capfd", "capfdbinary", "capsys", "capsysbinary"}
 
 
 def _ensure_only_one_capture_fixture(request, name):
-    fixtures = set(request.fixturenames) & capture_fixtures - set((name,))
+    fixtures = set(request.fixturenames) & capture_fixtures - {name}
     if fixtures:
         fixtures = sorted(fixtures)
         fixtures = fixtures[0] if len(fixtures) == 1 else fixtures
         raise request.raiseerror(
-            "cannot use {0} and {1} at the same time".format(
-                fixtures, name,
-            ),
+            "cannot use {} and {} at the same time".format(fixtures, name)
         )
 
 
 @pytest.fixture
 def capsys(request):
-    """Enable capturing of writes to sys.stdout/sys.stderr and make
+    """Enable capturing of writes to ``sys.stdout`` and ``sys.stderr`` and make
     captured output available via ``capsys.readouterr()`` method calls
-    which return a ``(out, err)`` tuple.  ``out`` and ``err`` will be ``text``
+    which return a ``(out, err)`` namedtuple.  ``out`` and ``err`` will be ``text``
     objects.
     """
-    _ensure_only_one_capture_fixture(request, 'capsys')
+    _ensure_only_one_capture_fixture(request, "capsys")
     with _install_capture_fixture_on_item(request, SysCapture) as fixture:
         yield fixture
 
 
 @pytest.fixture
 def capsysbinary(request):
-    """Enable capturing of writes to sys.stdout/sys.stderr and make
+    """Enable capturing of writes to ``sys.stdout`` and ``sys.stderr`` and make
     captured output available via ``capsys.readouterr()`` method calls
     which return a ``(out, err)`` tuple.  ``out`` and ``err`` will be ``bytes``
     objects.
     """
-    _ensure_only_one_capture_fixture(request, 'capsysbinary')
+    _ensure_only_one_capture_fixture(request, "capsysbinary")
     # Currently, the implementation uses the python3 specific `.buffer`
     # property of CaptureIO.
     if sys.version_info < (3,):
-        raise request.raiseerror('capsysbinary is only supported on python 3')
+        raise request.raiseerror("capsysbinary is only supported on python 3")
     with _install_capture_fixture_on_item(request, SysCaptureBinary) as fixture:
         yield fixture
 
 
 @pytest.fixture
 def capfd(request):
-    """Enable capturing of writes to file descriptors 1 and 2 and make
+    """Enable capturing of writes to file descriptors ``1`` and ``2`` and make
     captured output available via ``capfd.readouterr()`` method calls
     which return a ``(out, err)`` tuple.  ``out`` and ``err`` will be ``text``
     objects.
     """
-    _ensure_only_one_capture_fixture(request, 'capfd')
-    if not hasattr(os, 'dup'):
-        pytest.skip("capfd fixture needs os.dup function which is not available in this system")
+    _ensure_only_one_capture_fixture(request, "capfd")
+    if not hasattr(os, "dup"):
+        pytest.skip(
+            "capfd fixture needs os.dup function which is not available in this system"
+        )
     with _install_capture_fixture_on_item(request, FDCapture) as fixture:
         yield fixture
 
 
 @pytest.fixture
 def capfdbinary(request):
     """Enable capturing of write to file descriptors 1 and 2 and make
     captured output available via ``capfdbinary.readouterr`` method calls
     which return a ``(out, err)`` tuple.  ``out`` and ``err`` will be
     ``bytes`` objects.
     """
-    _ensure_only_one_capture_fixture(request, 'capfdbinary')
-    if not hasattr(os, 'dup'):
-        pytest.skip("capfdbinary fixture needs os.dup function which is not available in this system")
+    _ensure_only_one_capture_fixture(request, "capfdbinary")
+    if not hasattr(os, "dup"):
+        pytest.skip(
+            "capfdbinary fixture needs os.dup function which is not available in this system"
+        )
     with _install_capture_fixture_on_item(request, FDCaptureBinary) as fixture:
         yield fixture
 
 
 @contextlib.contextmanager
 def _install_capture_fixture_on_item(request, capture_class):
     """
     Context manager which creates a ``CaptureFixture`` instance and "installs" it on
     the item/node of the given request. Used by ``capsys`` and ``capfd``.
 
     The CaptureFixture is added as attribute of the item because it needs to accessed
     by ``CaptureManager`` during its ``pytest_runtest_*`` hooks.
     """
     request.node._capture_fixture = fixture = CaptureFixture(capture_class, request)
-    capmanager = request.config.pluginmanager.getplugin('capturemanager')
+    capmanager = request.config.pluginmanager.getplugin("capturemanager")
     # need to active this fixture right away in case it is being used by another fixture (setup phase)
     # if this fixture is being used only by a test function (call phase), then we wouldn't need this
     # activation, but it doesn't hurt
     capmanager.activate_fixture(request.node)
     yield fixture
     fixture.close()
     del request.node._capture_fixture
 
 
-class CaptureFixture:
+class CaptureFixture(object):
+    """
+    Object returned by :py:func:`capsys`, :py:func:`capsysbinary`, :py:func:`capfd` and :py:func:`capfdbinary`
+    fixtures.
+    """
+
     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)
+        self._capture = MultiCapture(
+            out=True, err=True, in_=False, Capture=self.captureclass
+        )
         self._capture.start_capturing()
 
     def close(self):
         cap = self.__dict__.pop("_capture", None)
         if cap is not None:
             self._outerr = cap.pop_outerr_to_orig()
             cap.stop_capturing()
 
     def readouterr(self):
+        """Read and return the captured output so far, resetting the internal buffer.
+
+        :return: captured content as a namedtuple with  ``out`` and ``err`` string attributes
+        """
         try:
             return self._capture.readouterr()
         except AttributeError:
             return self._outerr
 
     @contextlib.contextmanager
     def disabled(self):
+        """Temporarily disables capture while inside the 'with' block."""
         self._capture.suspend_capturing()
-        capmanager = self.request.config.pluginmanager.getplugin('capturemanager')
+        capmanager = self.request.config.pluginmanager.getplugin("capturemanager")
         capmanager.suspend_global_capture(item=None, in_=False)
         try:
             yield
         finally:
             capmanager.resume_global_capture()
             self._capture.resume_capturing()
 
 
 def safe_text_dupfile(f, mode, default_encoding="UTF8"):
-    """ return a open text file object that's a duplicate of f on the
+    """ return an open text file object that's a duplicate of f on the
         FD-level if possible.
     """
     encoding = getattr(f, "encoding", None)
     try:
         fd = f.fileno()
     except Exception:
         if "b" not in getattr(f, "mode", "") and hasattr(f, "encoding"):
             # we seem to have a text stream, let's just use it
@@ -332,17 +353,17 @@ class EncodedFile(object):
         self.encoding = encoding
 
     def write(self, obj):
         if isinstance(obj, six.text_type):
             obj = obj.encode(self.encoding, "replace")
         self.buffer.write(obj)
 
     def writelines(self, linelist):
-        data = ''.join(linelist)
+        data = "".join(linelist)
         self.write(data)
 
     @property
     def name(self):
         """Ensure that file.name is a string."""
         return repr(self.buffer)
 
     def __getattr__(self, name):
@@ -395,37 +416,39 @@ class MultiCapture(object):
         if self.err:
             self.err.resume()
         if hasattr(self, "_in_suspended"):
             self.in_.resume()
             del self._in_suspended
 
     def stop_capturing(self):
         """ stop capturing and reset capturing streams """
-        if hasattr(self, '_reset'):
+        if hasattr(self, "_reset"):
             raise ValueError("was already stopped")
         self._reset = True
         if self.out:
             self.out.done()
         if self.err:
             self.err.done()
         if self.in_:
             self.in_.done()
 
     def readouterr(self):
         """ return snapshot unicode value of stdout/stderr capturings. """
-        return CaptureResult(self.out.snap() if self.out is not None else "",
-                             self.err.snap() if self.err is not None else "")
+        return CaptureResult(
+            self.out.snap() if self.out is not None else "",
+            self.err.snap() if self.err is not None else "",
+        )
 
 
-class NoCapture:
+class NoCapture(object):
     __init__ = start = done = suspend = resume = lambda *args: None
 
 
-class FDCaptureBinary:
+class FDCaptureBinary(object):
     """Capture IO to/from a given os-level filedescriptor.
 
     snap() produces `bytes`
     """
 
     def __init__(self, targetfd, tmpfile=None):
         self.targetfd = targetfd
         try:
@@ -471,17 +494,17 @@ class FDCaptureBinary:
 
     def done(self):
         """ stop capturing, restore streams, return original capture file,
         seeked to position zero. """
         targetfd_save = self.__dict__.pop("targetfd_save")
         os.dup2(targetfd_save, self.targetfd)
         os.close(targetfd_save)
         self.syscapture.done()
-        self.tmpfile.close()
+        _attempt_to_close_capture_file(self.tmpfile)
 
     def suspend(self):
         self.syscapture.suspend()
         os.dup2(self.targetfd_save, self.targetfd)
 
     def resume(self):
         self.syscapture.resume()
         os.dup2(self.tmpfile_fd, self.targetfd)
@@ -493,25 +516,27 @@ class FDCaptureBinary:
         os.write(self.targetfd_save, data)
 
 
 class FDCapture(FDCaptureBinary):
     """Capture IO to/from a given os-level filedescriptor.
 
     snap() produces text
     """
+
     def snap(self):
         res = FDCaptureBinary.snap(self)
         enc = getattr(self.tmpfile, "encoding", None)
         if enc and isinstance(res, bytes):
             res = six.text_type(res, enc, "replace")
         return res
 
 
-class SysCapture:
+class SysCapture(object):
+
     def __init__(self, fd, tmpfile=None):
         name = patchsysdict[fd]
         self._old = getattr(sys, name)
         self.name = name
         if tmpfile is None:
             if name == "stdin":
                 tmpfile = DontReadFromInput()
             else:
@@ -525,82 +550,86 @@ class SysCapture:
         res = self.tmpfile.getvalue()
         self.tmpfile.seek(0)
         self.tmpfile.truncate()
         return res
 
     def done(self):
         setattr(sys, self.name, self._old)
         del self._old
-        self.tmpfile.close()
+        _attempt_to_close_capture_file(self.tmpfile)
 
     def suspend(self):
         setattr(sys, self.name, self._old)
 
     def resume(self):
         setattr(sys, self.name, self.tmpfile)
 
     def writeorg(self, data):
         self._old.write(data)
         self._old.flush()
 
 
 class SysCaptureBinary(SysCapture):
+
     def snap(self):
         res = self.tmpfile.buffer.getvalue()
         self.tmpfile.seek(0)
         self.tmpfile.truncate()
         return res
 
 
-class DontReadFromInput:
+class DontReadFromInput(six.Iterator):
     """Temporary stub class.  Ideally when stdin is accessed, the
     capturing should be turned off, with possibly all data captured
     so far sent to the screen.  This should be configurable, though,
     because in automated test runs it is better to crash than
     hang indefinitely.
     """
 
     encoding = None
 
     def read(self, *args):
         raise IOError("reading from stdin while output is captured")
+
     readline = read
     readlines = read
-    __iter__ = read
+    __next__ = read
+
+    def __iter__(self):
+        return self
 
     def fileno(self):
-        raise UnsupportedOperation("redirected stdin is pseudofile, "
-                                   "has no fileno()")
+        raise UnsupportedOperation("redirected stdin is pseudofile, " "has no fileno()")
 
     def isatty(self):
         return False
 
     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')
+            raise AttributeError("redirected stdin has no attribute buffer")
 
 
 def _colorama_workaround():
     """
     Ensure colorama is imported so that it attaches to the correct stdio
     handles on Windows.
 
     colorama uses the terminal on import time. So if something does the
     first import of colorama while I/O capture is active, colorama will
     fail in various ways.
     """
 
-    if not sys.platform.startswith('win32'):
+    if not sys.platform.startswith("win32"):
         return
     try:
         import colorama  # noqa
     except ImportError:
         pass
 
 
 def _readline_workaround():
@@ -617,17 +646,17 @@ def _readline_workaround():
     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'):
+    if not sys.platform.startswith("win32"):
         return
     try:
         import readline  # noqa
     except ImportError:
         pass
 
 
 def _py36_windowsconsoleio_workaround(stream):
@@ -647,37 +676,49 @@ def _py36_windowsconsoleio_workaround(st
     also means a different handle by replicating the logic in
     "Py_lifecycle.c:initstdio/create_stdio".
 
     :param stream: in practice ``sys.stdout`` or ``sys.stderr``, but given
         here as parameter for unittesting purposes.
 
     See https://github.com/pytest-dev/py/issues/103
     """
-    if not sys.platform.startswith('win32') or sys.version_info[:2] < (3, 6):
+    if not sys.platform.startswith("win32") or sys.version_info[:2] < (3, 6):
         return
 
     # bail out if ``stream`` doesn't seem like a proper ``io`` stream (#2666)
-    if not hasattr(stream, 'buffer'):
+    if not hasattr(stream, "buffer"):
         return
 
-    buffered = hasattr(stream.buffer, 'raw')
+    buffered = hasattr(stream.buffer, "raw")
     raw_stdout = stream.buffer.raw if buffered else stream.buffer
 
     if not isinstance(raw_stdout, io._WindowsConsoleIO):
         return
 
     def _reopen_stdio(f, mode):
-        if not buffered and mode[0] == 'w':
+        if not buffered and mode[0] == "w":
             buffering = 0
         else:
             buffering = -1
 
         return io.TextIOWrapper(
             open(os.dup(f.fileno()), mode, buffering),
             f.encoding,
             f.errors,
             f.newlines,
-            f.line_buffering)
+            f.line_buffering,
+        )
+
+    sys.__stdin__ = sys.stdin = _reopen_stdio(sys.stdin, "rb")
+    sys.__stdout__ = sys.stdout = _reopen_stdio(sys.stdout, "wb")
+    sys.__stderr__ = sys.stderr = _reopen_stdio(sys.stderr, "wb")
+
 
-    sys.__stdin__ = sys.stdin = _reopen_stdio(sys.stdin, 'rb')
-    sys.__stdout__ = sys.stdout = _reopen_stdio(sys.stdout, 'wb')
-    sys.__stderr__ = sys.stderr = _reopen_stdio(sys.stderr, 'wb')
+def _attempt_to_close_capture_file(f):
+    """Suppress IOError when closing the temporary file used for capturing streams in py27 (#2370)"""
+    if six.PY2:
+        try:
+            f.close()
+        except IOError:
+            pass
+    else:
+        f.close()
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/compat.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/compat.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/compat.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/compat.py
@@ -8,16 +8,18 @@ import functools
 import inspect
 import re
 import sys
 
 import py
 
 import _pytest
 from _pytest.outcomes import TEST_OUTCOME
+from six import text_type
+import six
 
 try:
     import enum
 except ImportError:  # pragma: no cover
     # Only available in Python 3.4+ or as a backport
     enum = None
 
 
@@ -31,63 +33,78 @@ else:
     from funcsigs import signature, Parameter as Parameter
 
 
 NoneType = type(None)
 NOTSET = object()
 
 PY35 = sys.version_info[:2] >= (3, 5)
 PY36 = sys.version_info[:2] >= (3, 6)
-MODULE_NOT_FOUND_ERROR = 'ModuleNotFoundError' if PY36 else 'ImportError'
+MODULE_NOT_FOUND_ERROR = "ModuleNotFoundError" if PY36 else "ImportError"
+
+if _PY3:
+    from collections.abc import MutableMapping as MappingMixin  # noqa
+    from collections.abc import Mapping, Sequence  # noqa
+else:
+    # those raise DeprecationWarnings in Python >=3.7
+    from collections import MutableMapping as MappingMixin  # noqa
+    from collections import Mapping, Sequence  # noqa
 
 
 def _format_args(func):
     return str(signature(func))
 
 
 isfunction = inspect.isfunction
 isclass = inspect.isclass
 # used to work around a python2 exception info leak
-exc_clear = getattr(sys, 'exc_clear', lambda: None)
+exc_clear = getattr(sys, "exc_clear", lambda: None)
 # The type of re.compile objects is not exposed in Python.
-REGEX_TYPE = type(re.compile(''))
+REGEX_TYPE = type(re.compile(""))
 
 
 def is_generator(func):
     genfunc = inspect.isgeneratorfunction(func)
     return genfunc and not iscoroutinefunction(func)
 
 
 def iscoroutinefunction(func):
     """Return True if func is a decorated coroutine function.
 
     Note: copied and modified from Python 3.5's builtin couroutines.py to avoid import asyncio directly,
     which in turns also initializes the "logging" module as side-effect (see issue #8).
     """
-    return (getattr(func, '_is_coroutine', False) or
-            (hasattr(inspect, 'iscoroutinefunction') and inspect.iscoroutinefunction(func)))
+    return (
+        getattr(func, "_is_coroutine", False)
+        or (
+            hasattr(inspect, "iscoroutinefunction")
+            and inspect.iscoroutinefunction(func)
+        )
+    )
 
 
 def getlocation(function, curdir):
     fn = py.path.local(inspect.getfile(function))
-    lineno = py.builtin._getcode(function).co_firstlineno
+    lineno = function.__code__.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])
+    mock_modules = [sys.modules.get("mock"), sys.modules.get("unittest.mock")]
+    if any(mock_modules):
+        sentinels = [m.DEFAULT for m in mock_modules if m is not None]
+        return len(
+            [p for p in patchings if not p.attribute_name and p.new in sentinels]
+        )
     return len(patchings)
 
 
 def getfuncargnames(function, is_method=False, cls=None):
     """Returns the names of a function's mandatory arguments.
 
     This should return the names of all function arguments that:
         * Aren't bound to an instance or type as in instance or class methods.
@@ -104,49 +121,72 @@ def getfuncargnames(function, is_method=
     the fixture names, and not try to obtain directly from the
     function object well after collection has occurred.
 
     """
     # The parameters attribute of a Signature object contains an
     # ordered mapping of parameter names to Parameter instances.  This
     # creates a tuple of the names of the parameters that don't have
     # defaults.
-    arg_names = tuple(p.name for p in signature(function).parameters.values()
-                      if (p.kind is Parameter.POSITIONAL_OR_KEYWORD or
-                          p.kind is Parameter.KEYWORD_ONLY) and
-                      p.default is Parameter.empty)
+    arg_names = tuple(
+        p.name
+        for p in signature(function).parameters.values()
+        if (
+            p.kind is Parameter.POSITIONAL_OR_KEYWORD
+            or p.kind is Parameter.KEYWORD_ONLY
+        )
+        and p.default is Parameter.empty
+    )
     # If this function should be treated as a bound method even though
     # it's passed as an unbound method or function, remove the first
     # parameter name.
-    if (is_method or
-        (cls and not isinstance(cls.__dict__.get(function.__name__, None),
-                                staticmethod))):
+    if (
+        is_method
+        or (
+            cls
+            and not isinstance(cls.__dict__.get(function.__name__, None), staticmethod)
+        )
+    ):
         arg_names = arg_names[1:]
     # Remove any names that will be replaced with mocks.
     if hasattr(function, "__wrapped__"):
         arg_names = arg_names[num_mock_patch_args(function):]
     return arg_names
 
 
+def get_default_arg_names(function):
+    # Note: this code intentionally mirrors the code at the beginning of getfuncargnames,
+    # to get the arguments which were excluded from its result because they had default values
+    return tuple(
+        p.name
+        for p in signature(function).parameters.values()
+        if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)
+        and p.default is not Parameter.empty
+    )
+
+
 if _PY3:
     STRING_TYPES = bytes, str
-    UNICODE_TYPES = str,
+    UNICODE_TYPES = six.text_type
 
     if PY35:
+
         def _bytes_to_ascii(val):
-            return val.decode('ascii', 'backslashreplace')
+            return val.decode("ascii", "backslashreplace")
+
     else:
+
         def _bytes_to_ascii(val):
             if val:
                 # source: http://goo.gl/bGsnwC
                 encoded_bytes, _ = codecs.escape_encode(val)
-                return encoded_bytes.decode('ascii')
+                return encoded_bytes.decode("ascii")
             else:
                 # empty bytes crashes codecs.escape_encode (#1087)
-                return ''
+                return ""
 
     def ascii_escaped(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
@@ -159,64 +199,66 @@ if _PY3:
            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):
             return _bytes_to_ascii(val)
         else:
-            return val.encode('unicode_escape').decode('ascii')
+            return val.encode("unicode_escape").decode("ascii")
+
+
 else:
-    STRING_TYPES = bytes, str, unicode
-    UNICODE_TYPES = unicode,
+    STRING_TYPES = six.string_types
+    UNICODE_TYPES = six.text_type
 
     def ascii_escaped(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')
+                return val.encode("ascii")
             except UnicodeDecodeError:
-                return val.encode('string-escape')
+                return val.encode("string-escape")
         else:
-            return val.encode('unicode-escape')
+            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.
     """
     start_obj = obj
     for i in range(100):
-        new_obj = getattr(obj, '__wrapped__', None)
+        new_obj = getattr(obj, "__wrapped__", None)
         if new_obj is None:
             break
         obj = new_obj
     else:
         raise ValueError(
-            ("could not find real function of {start}"
-             "\nstopped at {current}").format(
-                start=py.io.saferepr(start_obj),
-                current=py.io.saferepr(obj)))
+            ("could not find real function of {start}" "\nstopped at {current}").format(
+                start=py.io.saferepr(start_obj), current=py.io.saferepr(obj)
+            )
+        )
     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'):
+    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:
@@ -235,88 +277,95 @@ def safe_getattr(object, name, default):
     """
     try:
         return getattr(object, name, default)
     except TEST_OUTCOME:
         return default
 
 
 def _is_unittest_unexpected_success_a_failure():
-    """Return if the test suite should fail if a @expectedFailure unittest test PASSES.
+    """Return if the test suite should fail if an @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)
 
 
 if _PY3:
+
     def safe_str(v):
         """returns v as string"""
         return str(v)
+
+
 else:
+
     def safe_str(v):
         """returns v as string, converting to ascii if necessary"""
         try:
             return str(v)
         except UnicodeError:
-            if not isinstance(v, unicode):
-                v = unicode(v)
-            errors = 'replace'
-            return v.encode('utf-8', errors)
+            if not isinstance(v, text_type):
+                v = text_type(v)
+            errors = "replace"
+            return v.encode("utf-8", errors)
 
 
 COLLECT_FAKEMODULE_ATTRIBUTES = (
-    'Collector',
-    'Module',
-    'Generator',
-    'Function',
-    'Instance',
-    'Session',
-    'Item',
-    'Class',
-    'File',
-    '_fillfuncargs',
+    "Collector",
+    "Module",
+    "Generator",
+    "Function",
+    "Instance",
+    "Session",
+    "Item",
+    "Class",
+    "File",
+    "_fillfuncargs",
 )
 
 
 def _setup_collect_fakemodule():
     from types import ModuleType
     import pytest
-    pytest.collect = ModuleType('pytest.collect')
+
+    pytest.collect = ModuleType("pytest.collect")
     pytest.collect.__all__ = []  # used for setns
     for attr in COLLECT_FAKEMODULE_ATTRIBUTES:
         setattr(pytest.collect, attr, getattr(pytest, attr))
 
 
 if _PY2:
     # Without this the test_dupfile_on_textio will fail, otherwise CaptureIO could directly inherit from StringIO.
     from py.io import TextIO
 
     class CaptureIO(TextIO):
 
         @property
         def encoding(self):
-            return getattr(self, '_encoding', 'UTF-8')
+            return getattr(self, "_encoding", "UTF-8")
+
 
 else:
     import io
 
     class CaptureIO(io.TextIOWrapper):
+
         def __init__(self):
             super(CaptureIO, self).__init__(
-                io.BytesIO(),
-                encoding='UTF-8', newline='', write_through=True,
+                io.BytesIO(), encoding="UTF-8", newline="", write_through=True
             )
 
         def getvalue(self):
-            return self.buffer.getvalue().decode('UTF-8')
+            return self.buffer.getvalue().decode("UTF-8")
 
 
 class FuncargnamesCompatAttr(object):
     """ helper class so that Metafunc, Function and FixtureRequest
     don't need to each define the "funcargnames" compatibility attribute.
     """
+
     @property
     def funcargnames(self):
         """ alias attribute for ``fixturenames`` for pre-2.3 compatibility"""
         return self.fixturenames
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/config/__init__.py
@@ -0,0 +1,979 @@
+""" command line options, ini-file and conftest.py processing. """
+from __future__ import absolute_import, division, print_function
+import argparse
+import shlex
+import traceback
+import types
+import warnings
+import copy
+import six
+import py
+
+# DON't import pytest here because it causes import cycle troubles
+import sys
+import os
+from _pytest.outcomes import Skipped
+
+import _pytest._code
+import _pytest.hookspec  # the extension point definitions
+import _pytest.assertion
+from pluggy import PluginManager, HookimplMarker, HookspecMarker
+from _pytest.compat import safe_str
+from .exceptions import UsageError, PrintHelp
+from .findpaths import determine_setup, exists
+
+hookimpl = HookimplMarker("pytest")
+hookspec = HookspecMarker("pytest")
+
+# pytest startup
+#
+
+
+class ConftestImportFailure(Exception):
+
+    def __init__(self, path, excinfo):
+        Exception.__init__(self, path, excinfo)
+        self.path = path
+        self.excinfo = excinfo
+
+    def __str__(self):
+        etype, evalue, etb = self.excinfo
+        formatted = traceback.format_tb(etb)
+        # The level of the tracebacks we want to print is hand crafted :(
+        return repr(evalue) + "\n" + "".join(formatted[2:])
+
+
+def main(args=None, plugins=None):
+    """ return exit code, after performing an in-process test run.
+
+    :arg args: list of command line arguments.
+
+    :arg plugins: list of plugin objects to be auto-registered during
+                  initialization.
+    """
+    try:
+        try:
+            config = _prepareconfig(args, plugins)
+        except ConftestImportFailure as e:
+            tw = py.io.TerminalWriter(sys.stderr)
+            for line in traceback.format_exception(*e.excinfo):
+                tw.line(line.rstrip(), red=True)
+            tw.line("ERROR: could not load %s\n" % (e.path,), red=True)
+            return 4
+        else:
+            try:
+                return config.hook.pytest_cmdline_main(config=config)
+            finally:
+                config._ensure_unconfigure()
+    except UsageError as e:
+        tw = py.io.TerminalWriter(sys.stderr)
+        for msg in e.args:
+            tw.line("ERROR: {}\n".format(msg), red=True)
+        return 4
+
+
+class cmdline(object):  # NOQA compatibility namespace
+    main = staticmethod(main)
+
+
+def filename_arg(path, optname):
+    """ Argparse type validator for filename arguments.
+
+    :path: path of filename
+    :optname: name of the option
+    """
+    if os.path.isdir(path):
+        raise UsageError("{} must be a filename, given: {}".format(optname, path))
+    return path
+
+
+def directory_arg(path, optname):
+    """Argparse type validator for directory arguments.
+
+    :path: path of directory
+    :optname: name of the option
+    """
+    if not os.path.isdir(path):
+        raise UsageError("{} must be a directory, given: {}".format(optname, path))
+    return path
+
+
+default_plugins = (
+    "mark",
+    "main",
+    "terminal",
+    "runner",
+    "python",
+    "fixtures",
+    "debugging",
+    "unittest",
+    "capture",
+    "skipping",
+    "tmpdir",
+    "monkeypatch",
+    "recwarn",
+    "pastebin",
+    "helpconfig",
+    "nose",
+    "assertion",
+    "junitxml",
+    "resultlog",
+    "doctest",
+    "cacheprovider",
+    "freeze_support",
+    "setuponly",
+    "setupplan",
+    "warnings",
+    "logging",
+)
+
+
+builtin_plugins = set(default_plugins)
+builtin_plugins.add("pytester")
+
+
+def get_config():
+    # subsequent calls to main will create a fresh instance
+    pluginmanager = PytestPluginManager()
+    config = Config(pluginmanager)
+    for spec in default_plugins:
+        pluginmanager.import_plugin(spec)
+    return config
+
+
+def get_plugin_manager():
+    """
+    Obtain a new instance of the
+    :py:class:`_pytest.config.PytestPluginManager`, with default plugins
+    already loaded.
+
+    This function can be used by integration with other tools, like hooking
+    into pytest to run tests into an IDE.
+    """
+    return get_config().pluginmanager
+
+
+def _prepareconfig(args=None, plugins=None):
+    warning = None
+    if args is None:
+        args = sys.argv[1:]
+    elif isinstance(args, py.path.local):
+        args = [str(args)]
+    elif not isinstance(args, (tuple, list)):
+        if not isinstance(args, str):
+            raise ValueError("not a string or argument list: %r" % (args,))
+        args = shlex.split(args, posix=sys.platform != "win32")
+        from _pytest import deprecated
+
+        warning = deprecated.MAIN_STR_ARGS
+    config = get_config()
+    pluginmanager = config.pluginmanager
+    try:
+        if plugins:
+            for plugin in plugins:
+                if isinstance(plugin, six.string_types):
+                    pluginmanager.consider_pluginarg(plugin)
+                else:
+                    pluginmanager.register(plugin)
+        if warning:
+            config.warn("C1", warning)
+        return pluginmanager.hook.pytest_cmdline_parse(
+            pluginmanager=pluginmanager, args=args
+        )
+    except BaseException:
+        config._ensure_unconfigure()
+        raise
+
+
+class PytestPluginManager(PluginManager):
+    """
+    Overwrites :py:class:`pluggy.PluginManager <pluggy.PluginManager>` to add pytest-specific
+    functionality:
+
+    * loading plugins from the command line, ``PYTEST_PLUGINS`` env variable and
+      ``pytest_plugins`` global variables found in plugins being loaded;
+    * ``conftest.py`` loading during start-up;
+    """
+
+    def __init__(self):
+        super(PytestPluginManager, self).__init__("pytest")
+        self._conftest_plugins = set()
+
+        # state related to local conftest plugins
+        self._path2confmods = {}
+        self._conftestpath2mod = {}
+        self._confcutdir = None
+        self._noconftest = False
+        self._duplicatepaths = set()
+
+        self.add_hookspecs(_pytest.hookspec)
+        self.register(self)
+        if os.environ.get("PYTEST_DEBUG"):
+            err = sys.stderr
+            encoding = getattr(err, "encoding", "utf8")
+            try:
+                err = py.io.dupfile(err, encoding=encoding)
+            except Exception:
+                pass
+            self.trace.root.setwriter(err.write)
+            self.enable_tracing()
+
+        # Config._consider_importhook will set a real object if required.
+        self.rewrite_hook = _pytest.assertion.DummyRewriteHook()
+        # Used to know when we are importing conftests after the pytest_configure stage
+        self._configured = False
+
+    def addhooks(self, module_or_class):
+        """
+        .. deprecated:: 2.8
+
+        Use :py:meth:`pluggy.PluginManager.add_hookspecs <PluginManager.add_hookspecs>`
+        instead.
+        """
+        warning = dict(
+            code="I2",
+            fslocation=_pytest._code.getfslineno(sys._getframe(1)),
+            nodeid=None,
+            message="use pluginmanager.add_hookspecs instead of "
+            "deprecated addhooks() method.",
+        )
+        self._warn(warning)
+        return self.add_hookspecs(module_or_class)
+
+    def parse_hookimpl_opts(self, plugin, name):
+        # pytest hooks are always prefixed with pytest_
+        # so we avoid accessing possibly non-readable attributes
+        # (see issue #1073)
+        if not name.startswith("pytest_"):
+            return
+        # ignore some historic special names which can not be hooks anyway
+        if name == "pytest_plugins" or name.startswith("pytest_funcarg__"):
+            return
+
+        method = getattr(plugin, name)
+        opts = super(PytestPluginManager, self).parse_hookimpl_opts(plugin, name)
+
+        # collect unmarked hooks as long as they have the `pytest_' prefix
+        if opts is None and name.startswith("pytest_"):
+            opts = {}
+
+        if opts is not None:
+            for name in ("tryfirst", "trylast", "optionalhook", "hookwrapper"):
+                opts.setdefault(name, hasattr(method, name))
+        return opts
+
+    def parse_hookspec_opts(self, module_or_class, name):
+        opts = super(PytestPluginManager, self).parse_hookspec_opts(
+            module_or_class, name
+        )
+        if opts is None:
+            method = getattr(module_or_class, name)
+            if name.startswith("pytest_"):
+                opts = {
+                    "firstresult": hasattr(method, "firstresult"),
+                    "historic": hasattr(method, "historic"),
+                }
+        return opts
+
+    def register(self, plugin, name=None):
+        if name in ["pytest_catchlog", "pytest_capturelog"]:
+            self._warn(
+                "{} plugin has been merged into the core, "
+                "please remove it from your requirements.".format(
+                    name.replace("_", "-")
+                )
+            )
+            return
+        ret = super(PytestPluginManager, self).register(plugin, name)
+        if ret:
+            self.hook.pytest_plugin_registered.call_historic(
+                kwargs=dict(plugin=plugin, manager=self)
+            )
+
+            if isinstance(plugin, types.ModuleType):
+                self.consider_module(plugin)
+        return ret
+
+    def getplugin(self, name):
+        # support deprecated naming because plugins (xdist e.g.) use it
+        return self.get_plugin(name)
+
+    def hasplugin(self, name):
+        """Return True if the plugin with the given name is registered."""
+        return bool(self.get_plugin(name))
+
+    def pytest_configure(self, config):
+        # XXX now that the pluginmanager exposes hookimpl(tryfirst...)
+        # we should remove tryfirst/trylast as markers
+        config.addinivalue_line(
+            "markers",
+            "tryfirst: mark a hook implementation function such that the "
+            "plugin machinery will try to call it first/as early as possible.",
+        )
+        config.addinivalue_line(
+            "markers",
+            "trylast: mark a hook implementation function such that the "
+            "plugin machinery will try to call it last/as late as possible.",
+        )
+        self._configured = True
+
+    def _warn(self, message):
+        kwargs = message if isinstance(message, dict) else {
+            "code": "I1", "message": message, "fslocation": None, "nodeid": None
+        }
+        self.hook.pytest_logwarning.call_historic(kwargs=kwargs)
+
+    #
+    # internal API for local conftest plugin handling
+    #
+    def _set_initial_conftests(self, namespace):
+        """ load initial conftest files given a preparsed "namespace".
+            As conftest files may add their own command line options
+            which have arguments ('--my-opt somepath') we might get some
+            false positives.  All builtin and 3rd party plugins will have
+            been loaded, however, so common options will not confuse our logic
+            here.
+        """
+        current = py.path.local()
+        self._confcutdir = current.join(
+            namespace.confcutdir, abs=True
+        ) if namespace.confcutdir else None
+        self._noconftest = namespace.noconftest
+        testpaths = namespace.file_or_dir
+        foundanchor = False
+        for path in testpaths:
+            path = str(path)
+            # remove node-id syntax
+            i = path.find("::")
+            if i != -1:
+                path = path[:i]
+            anchor = current.join(path, abs=1)
+            if exists(anchor):  # we found some file object
+                self._try_load_conftest(anchor)
+                foundanchor = True
+        if not foundanchor:
+            self._try_load_conftest(current)
+
+    def _try_load_conftest(self, anchor):
+        self._getconftestmodules(anchor)
+        # let's also consider test* subdirs
+        if anchor.check(dir=1):
+            for x in anchor.listdir("test*"):
+                if x.check(dir=1):
+                    self._getconftestmodules(x)
+
+    def _getconftestmodules(self, path):
+        if self._noconftest:
+            return []
+        try:
+            return self._path2confmods[path]
+        except KeyError:
+            if path.isfile():
+                clist = self._getconftestmodules(path.dirpath())
+            else:
+                # XXX these days we may rather want to use config.rootdir
+                # and allow users to opt into looking into the rootdir parent
+                # directories instead of requiring to specify confcutdir
+                clist = []
+                for parent in path.parts():
+                    if self._confcutdir and self._confcutdir.relto(parent):
+                        continue
+                    conftestpath = parent.join("conftest.py")
+                    if conftestpath.isfile():
+                        mod = self._importconftest(conftestpath)
+                        clist.append(mod)
+
+            self._path2confmods[path] = clist
+            return clist
+
+    def _rget_with_confmod(self, name, path):
+        modules = self._getconftestmodules(path)
+        for mod in reversed(modules):
+            try:
+                return mod, getattr(mod, name)
+            except AttributeError:
+                continue
+        raise KeyError(name)
+
+    def _importconftest(self, conftestpath):
+        try:
+            return self._conftestpath2mod[conftestpath]
+        except KeyError:
+            pkgpath = conftestpath.pypkgpath()
+            if pkgpath is None:
+                _ensure_removed_sysmodule(conftestpath.purebasename)
+            try:
+                mod = conftestpath.pyimport()
+                if hasattr(mod, "pytest_plugins") and self._configured:
+                    from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST
+
+                    warnings.warn(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST)
+            except Exception:
+                raise ConftestImportFailure(conftestpath, sys.exc_info())
+
+            self._conftest_plugins.add(mod)
+            self._conftestpath2mod[conftestpath] = mod
+            dirpath = conftestpath.dirpath()
+            if dirpath in self._path2confmods:
+                for path, mods in self._path2confmods.items():
+                    if path and path.relto(dirpath) or path == dirpath:
+                        assert mod not in mods
+                        mods.append(mod)
+            self.trace("loaded conftestmodule %r" % (mod))
+            self.consider_conftest(mod)
+            return mod
+
+    #
+    # API for bootstrapping plugin loading
+    #
+    #
+
+    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:]
+            self.set_blocked(name)
+            if not name.startswith("pytest_"):
+                self.set_blocked("pytest_" + name)
+        else:
+            self.import_plugin(arg)
+
+    def consider_conftest(self, conftestmodule):
+        self.register(conftestmodule, name=conftestmodule.__file__)
+
+    def consider_env(self):
+        self._import_plugin_specs(os.environ.get("PYTEST_PLUGINS"))
+
+    def consider_module(self, mod):
+        self._import_plugin_specs(getattr(mod, "pytest_plugins", []))
+
+    def _import_plugin_specs(self, spec):
+        plugins = _get_plugin_specs_as_list(spec)
+        for import_spec in plugins:
+            self.import_plugin(import_spec)
+
+    def import_plugin(self, modname):
+        # most often modname refers to builtin modules, e.g. "pytester",
+        # "terminal" or "capture".  Those plugins are registered under their
+        # basename for historic purposes but must be imported with the
+        # _pytest prefix.
+        assert isinstance(modname, (six.text_type, str)), (
+            "module name as text required, got %r" % modname
+        )
+        modname = str(modname)
+        if self.is_blocked(modname) or self.get_plugin(modname) is not None:
+            return
+        if modname in builtin_plugins:
+            importspec = "_pytest." + modname
+        else:
+            importspec = modname
+        self.rewrite_hook.mark_rewrite(importspec)
+        try:
+            __import__(importspec)
+        except ImportError as e:
+            new_exc_type = ImportError
+            new_exc_message = 'Error importing plugin "%s": %s' % (
+                modname, safe_str(e.args[0])
+            )
+            new_exc = new_exc_type(new_exc_message)
+
+            six.reraise(new_exc_type, new_exc, sys.exc_info()[2])
+
+        except Skipped as e:
+            self._warn("skipped plugin %r: %s" % ((modname, e.msg)))
+        else:
+            mod = sys.modules[importspec]
+            self.register(mod, modname)
+
+
+def _get_plugin_specs_as_list(specs):
+    """
+    Parses a list of "plugin specs" and returns a list of plugin names.
+
+    Plugin specs can be given as a list of strings separated by "," or already as a list/tuple in
+    which case it is returned as a list. Specs can also be `None` in which case an
+    empty list is returned.
+    """
+    if specs is not None:
+        if isinstance(specs, str):
+            specs = specs.split(",") if specs else []
+        if not isinstance(specs, (list, tuple)):
+            raise UsageError(
+                "Plugin specs must be a ','-separated string or a "
+                "list/tuple of strings for plugin names. Given: %r" % specs
+            )
+        return list(specs)
+    return []
+
+
+def _ensure_removed_sysmodule(modname):
+    try:
+        del sys.modules[modname]
+    except KeyError:
+        pass
+
+
+class Notset(object):
+
+    def __repr__(self):
+        return "<NOTSET>"
+
+
+notset = Notset()
+
+
+def _iter_rewritable_modules(package_files):
+    for fn in package_files:
+        is_simple_module = "/" not in fn and fn.endswith(".py")
+        is_package = fn.count("/") == 1 and fn.endswith("__init__.py")
+        if is_simple_module:
+            module_name, _ = os.path.splitext(fn)
+            yield module_name
+        elif is_package:
+            package_name = os.path.dirname(fn)
+            yield package_name
+
+
+class Config(object):
+    """ access to configuration values, pluginmanager and plugin hooks.  """
+
+    def __init__(self, pluginmanager):
+        #: access to command line option as attributes.
+        #: (deprecated), use :py:func:`getoption() <_pytest.config.Config.getoption>` instead
+        self.option = argparse.Namespace()
+        from .argparsing import Parser, FILE_OR_DIR
+
+        _a = FILE_OR_DIR
+        self._parser = Parser(
+            usage="%%(prog)s [options] [%s] [%s] [...]" % (_a, _a),
+            processopt=self._processopt,
+        )
+        #: a pluginmanager instance
+        self.pluginmanager = pluginmanager
+        self.trace = self.pluginmanager.trace.root.get("config")
+        self.hook = self.pluginmanager.hook
+        self._inicache = {}
+        self._override_ini = ()
+        self._opt2dest = {}
+        self._cleanup = []
+        self._warn = self.pluginmanager._warn
+        self.pluginmanager.register(self, "pytestconfig")
+        self._configured = False
+
+        def do_setns(dic):
+            import pytest
+
+            setns(pytest, dic)
+
+        self.hook.pytest_namespace.call_historic(do_setns, {})
+        self.hook.pytest_addoption.call_historic(kwargs=dict(parser=self._parser))
+
+    def add_cleanup(self, func):
+        """ Add a function to be called when the config object gets out of
+        use (usually coninciding with pytest_unconfigure)."""
+        self._cleanup.append(func)
+
+    def _do_configure(self):
+        assert not self._configured
+        self._configured = True
+        self.hook.pytest_configure.call_historic(kwargs=dict(config=self))
+
+    def _ensure_unconfigure(self):
+        if self._configured:
+            self._configured = False
+            self.hook.pytest_unconfigure(config=self)
+            self.hook.pytest_configure._call_history = []
+        while self._cleanup:
+            fin = self._cleanup.pop()
+            fin()
+
+    def warn(self, code, message, fslocation=None, nodeid=None):
+        """ generate a warning for this test session. """
+        self.hook.pytest_logwarning.call_historic(
+            kwargs=dict(
+                code=code, message=message, fslocation=fslocation, nodeid=nodeid
+            )
+        )
+
+    def get_terminal_writer(self):
+        return self.pluginmanager.get_plugin("terminalreporter")._tw
+
+    def pytest_cmdline_parse(self, pluginmanager, args):
+        # REF1 assert self == pluginmanager.config, (self, pluginmanager.config)
+        self.parse(args)
+        return self
+
+    def notify_exception(self, excinfo, option=None):
+        if option and option.fulltrace:
+            style = "long"
+        else:
+            style = "native"
+        excrepr = excinfo.getrepr(
+            funcargs=True, showlocals=getattr(option, "showlocals", False), style=style
+        )
+        res = self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo)
+        if not any(res):
+            for line in str(excrepr).split("\n"):
+                sys.stderr.write("INTERNALERROR> %s\n" % line)
+                sys.stderr.flush()
+
+    def cwd_relative_nodeid(self, nodeid):
+        # nodeid's are relative to the rootpath, compute relative to cwd
+        if self.invocation_dir != self.rootdir:
+            fullpath = self.rootdir.join(nodeid)
+            nodeid = self.invocation_dir.bestrelpath(fullpath)
+        return nodeid
+
+    @classmethod
+    def fromdictargs(cls, option_dict, args):
+        """ constructor useable for subprocesses. """
+        config = get_config()
+        config.option.__dict__.update(option_dict)
+        config.parse(args, addopts=False)
+        for x in config.option.plugins:
+            config.pluginmanager.consider_pluginarg(x)
+        return config
+
+    def _processopt(self, opt):
+        for name in opt._short_opts + opt._long_opts:
+            self._opt2dest[name] = opt.dest
+
+        if hasattr(opt, "default") and opt.dest:
+            if not hasattr(self.option, opt.dest):
+                setattr(self.option, opt.dest, opt.default)
+
+    @hookimpl(trylast=True)
+    def pytest_load_initial_conftests(self, early_config):
+        self.pluginmanager._set_initial_conftests(early_config.known_args_namespace)
+
+    def _initini(self, args):
+        ns, unknown_args = self._parser.parse_known_and_unknown_args(
+            args, namespace=copy.copy(self.option)
+        )
+        r = determine_setup(
+            ns.inifilename,
+            ns.file_or_dir + unknown_args,
+            warnfunc=self.warn,
+            rootdir_cmd_arg=ns.rootdir or None,
+        )
+        self.rootdir, self.inifile, self.inicfg = r
+        self._parser.extra_info["rootdir"] = self.rootdir
+        self._parser.extra_info["inifile"] = self.inifile
+        self.invocation_dir = py.path.local()
+        self._parser.addini("addopts", "extra command line options", "args")
+        self._parser.addini("minversion", "minimally required pytest version")
+        self._override_ini = ns.override_ini or ()
+
+    def _consider_importhook(self, args):
+        """Install the PEP 302 import hook if using assertion rewriting.
+
+        Needs to parse the --assert=<mode> option from the commandline
+        and find all the installed plugins to mark them for rewriting
+        by the importhook.
+        """
+        ns, unknown_args = self._parser.parse_known_and_unknown_args(args)
+        mode = ns.assertmode
+        if mode == "rewrite":
+            try:
+                hook = _pytest.assertion.install_importhook(self)
+            except SystemError:
+                mode = "plain"
+            else:
+                self._mark_plugins_for_rewrite(hook)
+        _warn_about_missing_assertion(mode)
+
+    def _mark_plugins_for_rewrite(self, hook):
+        """
+        Given an importhook, mark for rewrite any top-level
+        modules or packages in the distribution package for
+        all pytest plugins.
+        """
+        import pkg_resources
+
+        self.pluginmanager.rewrite_hook = hook
+
+        # 'RECORD' available for plugins installed normally (pip install)
+        # 'SOURCES.txt' available for plugins installed in dev mode (pip install -e)
+        # for installed plugins 'SOURCES.txt' returns an empty list, and vice-versa
+        # so it shouldn't be an issue
+        metadata_files = "RECORD", "SOURCES.txt"
+
+        package_files = (
+            entry.split(",")[0]
+            for entrypoint in pkg_resources.iter_entry_points("pytest11")
+            for metadata in metadata_files
+            for entry in entrypoint.dist._get_metadata(metadata)
+        )
+
+        for name in _iter_rewritable_modules(package_files):
+            hook.mark_rewrite(name)
+
+    def _preparse(self, args, addopts=True):
+        if addopts:
+            args[:] = shlex.split(os.environ.get("PYTEST_ADDOPTS", "")) + args
+        self._initini(args)
+        if addopts:
+            args[:] = self.getini("addopts") + args
+        self._checkversion()
+        self._consider_importhook(args)
+        self.pluginmanager.consider_preparse(args)
+        self.pluginmanager.load_setuptools_entrypoints("pytest11")
+        self.pluginmanager.consider_env()
+        self.known_args_namespace = ns = self._parser.parse_known_args(
+            args, namespace=copy.copy(self.option)
+        )
+        if self.known_args_namespace.confcutdir is None and self.inifile:
+            confcutdir = py.path.local(self.inifile).dirname
+            self.known_args_namespace.confcutdir = confcutdir
+        try:
+            self.hook.pytest_load_initial_conftests(
+                early_config=self, args=args, parser=self._parser
+            )
+        except ConftestImportFailure:
+            e = sys.exc_info()[1]
+            if ns.help or ns.version:
+                # we don't want to prevent --help/--version to work
+                # so just let is pass and print a warning at the end
+                self._warn("could not load initial conftests (%s)\n" % e.path)
+            else:
+                raise
+
+    def _checkversion(self):
+        import pytest
+
+        minver = self.inicfg.get("minversion", None)
+        if minver:
+            ver = minver.split(".")
+            myver = pytest.__version__.split(".")
+            if myver < ver:
+                raise pytest.UsageError(
+                    "%s:%d: requires pytest-%s, actual pytest-%s'"
+                    % (
+                        self.inicfg.config.path,
+                        self.inicfg.lineof("minversion"),
+                        minver,
+                        pytest.__version__,
+                    )
+                )
+
+    def parse(self, args, addopts=True):
+        # parse given cmdline arguments into this config object.
+        assert not hasattr(
+            self, "args"
+        ), "can only parse cmdline args at most once per Config object"
+        self._origargs = args
+        self.hook.pytest_addhooks.call_historic(
+            kwargs=dict(pluginmanager=self.pluginmanager)
+        )
+        self._preparse(args, addopts=addopts)
+        # XXX deprecated hook:
+        self.hook.pytest_cmdline_preparse(config=self, args=args)
+        self._parser.after_preparse = True
+        try:
+            args = self._parser.parse_setoption(
+                args, self.option, namespace=self.option
+            )
+            if not args:
+                cwd = os.getcwd()
+                if cwd == self.rootdir:
+                    args = self.getini("testpaths")
+                if not args:
+                    args = [cwd]
+            self.args = args
+        except PrintHelp:
+            pass
+
+    def addinivalue_line(self, name, line):
+        """ add a line to an ini-file option. The option must have been
+        declared but might not yet be set in which case the line becomes the
+        the first line in its value. """
+        x = self.getini(name)
+        assert isinstance(x, list)
+        x.append(line)  # modifies the cached list inline
+
+    def getini(self, name):
+        """ return configuration value from an :ref:`ini file <inifiles>`. If the
+        specified name hasn't been registered through a prior
+        :py:func:`parser.addini <_pytest.config.Parser.addini>`
+        call (usually from a plugin), a ValueError is raised. """
+        try:
+            return self._inicache[name]
+        except KeyError:
+            self._inicache[name] = val = self._getini(name)
+            return val
+
+    def _getini(self, name):
+        try:
+            description, type, default = self._parser._inidict[name]
+        except KeyError:
+            raise ValueError("unknown configuration value: %r" % (name,))
+        value = self._get_override_ini_value(name)
+        if value is None:
+            try:
+                value = self.inicfg[name]
+            except KeyError:
+                if default is not None:
+                    return default
+                if type is None:
+                    return ""
+                return []
+        if type == "pathlist":
+            dp = py.path.local(self.inicfg.config.path).dirpath()
+            values = []
+            for relpath in shlex.split(value):
+                values.append(dp.join(relpath, abs=True))
+            return values
+        elif type == "args":
+            return shlex.split(value)
+        elif type == "linelist":
+            return [t for t in map(lambda x: x.strip(), value.split("\n")) if t]
+        elif type == "bool":
+            return bool(_strtobool(value.strip()))
+        else:
+            assert type is None
+            return value
+
+    def _getconftest_pathlist(self, name, path):
+        try:
+            mod, relroots = self.pluginmanager._rget_with_confmod(name, path)
+        except KeyError:
+            return None
+        modpath = py.path.local(mod.__file__).dirpath()
+        values = []
+        for relroot in relroots:
+            if not isinstance(relroot, py.path.local):
+                relroot = relroot.replace("/", py.path.local.sep)
+                relroot = modpath.join(relroot, abs=True)
+            values.append(relroot)
+        return values
+
+    def _get_override_ini_value(self, name):
+        value = None
+        # override_ini is a list of "ini=value" options
+        # always use the last item if multiple values are set for same ini-name,
+        # e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2
+        for ini_config in self._override_ini:
+            try:
+                key, user_ini_value = ini_config.split("=", 1)
+            except ValueError:
+                raise UsageError("-o/--override-ini expects option=value style.")
+            else:
+                if key == name:
+                    value = user_ini_value
+        return value
+
+    def getoption(self, name, default=notset, skip=False):
+        """ return command line option value.
+
+        :arg name: name of the option.  You may also specify
+            the literal ``--OPT`` option instead of the "dest" option name.
+        :arg default: default value if no option of that name exists.
+        :arg skip: if True raise pytest.skip if option does not exists
+            or has a None value.
+        """
+        name = self._opt2dest.get(name, name)
+        try:
+            val = getattr(self.option, name)
+            if val is None and skip:
+                raise AttributeError(name)
+            return val
+        except AttributeError:
+            if default is not notset:
+                return default
+            if skip:
+                import pytest
+
+                pytest.skip("no %r option found" % (name,))
+            raise ValueError("no option named %r" % (name,))
+
+    def getvalue(self, name, path=None):
+        """ (deprecated, use getoption()) """
+        return self.getoption(name)
+
+    def getvalueorskip(self, name, path=None):
+        """ (deprecated, use getoption(skip=True)) """
+        return self.getoption(name, skip=True)
+
+
+def _assertion_supported():
+    try:
+        assert False
+    except AssertionError:
+        return True
+    else:
+        return False
+
+
+def _warn_about_missing_assertion(mode):
+    if not _assertion_supported():
+        if mode == "plain":
+            sys.stderr.write(
+                "WARNING: ASSERTIONS ARE NOT EXECUTED"
+                " and FAILING TESTS WILL PASS.  Are you"
+                " using python -O?"
+            )
+        else:
+            sys.stderr.write(
+                "WARNING: assertions not in test modules or"
+                " plugins will be ignored"
+                " because assert statements are not executed "
+                "by the underlying Python interpreter "
+                "(are you using python -O?)\n"
+            )
+
+
+def setns(obj, dic):
+    import pytest
+
+    for name, value in dic.items():
+        if isinstance(value, dict):
+            mod = getattr(obj, name, None)
+            if mod is None:
+                modname = "pytest.%s" % name
+                mod = types.ModuleType(modname)
+                sys.modules[modname] = mod
+                mod.__all__ = []
+                setattr(obj, name, mod)
+            obj.__all__.append(name)
+            setns(mod, value)
+        else:
+            setattr(obj, name, value)
+            obj.__all__.append(name)
+            # if obj != pytest:
+            #    pytest.__all__.append(name)
+            setattr(pytest, name, value)
+
+
+def create_terminal_writer(config, *args, **kwargs):
+    """Create a TerminalWriter instance configured according to the options
+    in the config object. Every code which requires a TerminalWriter object
+    and has access to a config object should use this function.
+    """
+    tw = py.io.TerminalWriter(*args, **kwargs)
+    if config.option.color == "yes":
+        tw.hasmarkup = True
+    if config.option.color == "no":
+        tw.hasmarkup = False
+    return tw
+
+
+def _strtobool(val):
+    """Convert a string representation of truth to true (1) or false (0).
+
+    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
+    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
+    'val' is anything else.
+
+    .. note:: copied from distutils.util
+    """
+    val = val.lower()
+    if val in ("y", "yes", "t", "true", "on", "1"):
+        return 1
+    elif val in ("n", "no", "f", "false", "off", "0"):
+        return 0
+    else:
+        raise ValueError("invalid truth value %r" % (val,))
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/config/argparsing.py
@@ -0,0 +1,394 @@
+import six
+import warnings
+import argparse
+
+FILE_OR_DIR = "file_or_dir"
+
+
+class Parser(object):
+    """ Parser for command line arguments and ini-file values.
+
+    :ivar extra_info: dict of generic param -> value to display in case
+        there's an error processing the command line arguments.
+    """
+
+    def __init__(self, usage=None, processopt=None):
+        self._anonymous = OptionGroup("custom options", parser=self)
+        self._groups = []
+        self._processopt = processopt
+        self._usage = usage
+        self._inidict = {}
+        self._ininames = []
+        self.extra_info = {}
+
+    def processoption(self, option):
+        if self._processopt:
+            if option.dest:
+                self._processopt(option)
+
+    def getgroup(self, name, description="", after=None):
+        """ get (or create) a named option Group.
+
+        :name: name of the option group.
+        :description: long description for --help output.
+        :after: name of other group, used for ordering --help output.
+
+        The returned group object has an ``addoption`` method with the same
+        signature as :py:func:`parser.addoption
+        <_pytest.config.Parser.addoption>` but will be shown in the
+        respective group in the output of ``pytest. --help``.
+        """
+        for group in self._groups:
+            if group.name == name:
+                return group
+        group = OptionGroup(name, description, parser=self)
+        i = 0
+        for i, grp in enumerate(self._groups):
+            if grp.name == after:
+                break
+        self._groups.insert(i + 1, group)
+        return group
+
+    def addoption(self, *opts, **attrs):
+        """ register a command line option.
+
+        :opts: option names, can be short or long options.
+        :attrs: same attributes which the ``add_option()`` function of the
+           `argparse library
+           <http://docs.python.org/2/library/argparse.html>`_
+           accepts.
+
+        After command line parsing options are available on the pytest config
+        object via ``config.option.NAME`` where ``NAME`` is usually set
+        by passing a ``dest`` attribute, for example
+        ``addoption("--long", dest="NAME", ...)``.
+        """
+        self._anonymous.addoption(*opts, **attrs)
+
+    def parse(self, args, namespace=None):
+        from _pytest._argcomplete import try_argcomplete
+
+        self.optparser = self._getparser()
+        try_argcomplete(self.optparser)
+        return self.optparser.parse_args([str(x) for x in args], namespace=namespace)
+
+    def _getparser(self):
+        from _pytest._argcomplete import filescompleter
+
+        optparser = MyOptionParser(self, self.extra_info)
+        groups = self._groups + [self._anonymous]
+        for group in groups:
+            if group.options:
+                desc = group.description or group.name
+                arggroup = optparser.add_argument_group(desc)
+                for option in group.options:
+                    n = option.names()
+                    a = option.attrs()
+                    arggroup.add_argument(*n, **a)
+        # bash like autocompletion for dirs (appending '/')
+        optparser.add_argument(FILE_OR_DIR, nargs="*").completer = filescompleter
+        return optparser
+
+    def parse_setoption(self, args, option, namespace=None):
+        parsedoption = self.parse(args, namespace=namespace)
+        for name, value in parsedoption.__dict__.items():
+            setattr(option, name, value)
+        return getattr(parsedoption, FILE_OR_DIR)
+
+    def parse_known_args(self, args, namespace=None):
+        """parses and returns a namespace object with known arguments at this
+        point.
+        """
+        return self.parse_known_and_unknown_args(args, namespace=namespace)[0]
+
+    def parse_known_and_unknown_args(self, args, namespace=None):
+        """parses and returns a namespace object with known arguments, and
+        the remaining arguments unknown at this point.
+        """
+        optparser = self._getparser()
+        args = [str(x) for x in args]
+        return optparser.parse_known_args(args, namespace=namespace)
+
+    def addini(self, name, help, type=None, default=None):
+        """ register an ini-file option.
+
+        :name: name of the ini-variable
+        :type: type of the variable, can be ``pathlist``, ``args``, ``linelist``
+               or ``bool``.
+        :default: default value if no ini-file option exists but is queried.
+
+        The value of ini-variables can be retrieved via a call to
+        :py:func:`config.getini(name) <_pytest.config.Config.getini>`.
+        """
+        assert type in (None, "pathlist", "args", "linelist", "bool")
+        self._inidict[name] = (help, type, default)
+        self._ininames.append(name)
+
+
+class ArgumentError(Exception):
+    """
+    Raised if an Argument instance is created with invalid or
+    inconsistent arguments.
+    """
+
+    def __init__(self, msg, option):
+        self.msg = msg
+        self.option_id = str(option)
+
+    def __str__(self):
+        if self.option_id:
+            return "option %s: %s" % (self.option_id, self.msg)
+        else:
+            return self.msg
+
+
+class Argument(object):
+    """class that mimics the necessary behaviour of optparse.Option
+
+    its currently a least effort implementation
+    and ignoring choices and integer prefixes
+    https://docs.python.org/3/library/optparse.html#optparse-standard-option-types
+    """
+    _typ_map = {"int": int, "string": str, "float": float, "complex": complex}
+
+    def __init__(self, *names, **attrs):
+        """store parms in private vars for use in add_argument"""
+        self._attrs = attrs
+        self._short_opts = []
+        self._long_opts = []
+        self.dest = attrs.get("dest")
+        if "%default" in (attrs.get("help") or ""):
+            warnings.warn(
+                'pytest now uses argparse. "%default" should be'
+                ' changed to "%(default)s" ',
+                DeprecationWarning,
+                stacklevel=3,
+            )
+        try:
+            typ = attrs["type"]
+        except KeyError:
+            pass
+        else:
+            # this might raise a keyerror as well, don't want to catch that
+            if isinstance(typ, six.string_types):
+                if typ == "choice":
+                    warnings.warn(
+                        "type argument to addoption() is a string %r."
+                        " For parsearg this is optional and when supplied"
+                        " should be a type."
+                        " (options: %s)" % (typ, names),
+                        DeprecationWarning,
+                        stacklevel=3,
+                    )
+                    # argparse expects a type here take it from
+                    # the type of the first element
+                    attrs["type"] = type(attrs["choices"][0])
+                else:
+                    warnings.warn(
+                        "type argument to addoption() is a string %r."
+                        " For parsearg this should be a type."
+                        " (options: %s)" % (typ, names),
+                        DeprecationWarning,
+                        stacklevel=3,
+                    )
+                    attrs["type"] = Argument._typ_map[typ]
+                # used in test_parseopt -> test_parse_defaultgetter
+                self.type = attrs["type"]
+            else:
+                self.type = typ
+        try:
+            # attribute existence is tested in Config._processopt
+            self.default = attrs["default"]
+        except KeyError:
+            pass
+        self._set_opt_strings(names)
+        if not self.dest:
+            if self._long_opts:
+                self.dest = self._long_opts[0][2:].replace("-", "_")
+            else:
+                try:
+                    self.dest = self._short_opts[0][1:]
+                except IndexError:
+                    raise ArgumentError("need a long or short option", self)
+
+    def names(self):
+        return self._short_opts + self._long_opts
+
+    def attrs(self):
+        # update any attributes set by processopt
+        attrs = "default dest help".split()
+        if self.dest:
+            attrs.append(self.dest)
+        for attr in attrs:
+            try:
+                self._attrs[attr] = getattr(self, attr)
+            except AttributeError:
+                pass
+        if self._attrs.get("help"):
+            a = self._attrs["help"]
+            a = a.replace("%default", "%(default)s")
+            # a = a.replace('%prog', '%(prog)s')
+            self._attrs["help"] = a
+        return self._attrs
+
+    def _set_opt_strings(self, opts):
+        """directly from optparse
+
+        might not be necessary as this is passed to argparse later on"""
+        for opt in opts:
+            if len(opt) < 2:
+                raise ArgumentError(
+                    "invalid option string %r: "
+                    "must be at least two characters long" % opt,
+                    self,
+                )
+            elif len(opt) == 2:
+                if not (opt[0] == "-" and opt[1] != "-"):
+                    raise ArgumentError(
+                        "invalid short option string %r: "
+                        "must be of the form -x, (x any non-dash char)" % opt,
+                        self,
+                    )
+                self._short_opts.append(opt)
+            else:
+                if not (opt[0:2] == "--" and opt[2] != "-"):
+                    raise ArgumentError(
+                        "invalid long option string %r: "
+                        "must start with --, followed by non-dash" % opt,
+                        self,
+                    )
+                self._long_opts.append(opt)
+
+    def __repr__(self):
+        args = []
+        if self._short_opts:
+            args += ["_short_opts: " + repr(self._short_opts)]
+        if self._long_opts:
+            args += ["_long_opts: " + repr(self._long_opts)]
+        args += ["dest: " + repr(self.dest)]
+        if hasattr(self, "type"):
+            args += ["type: " + repr(self.type)]
+        if hasattr(self, "default"):
+            args += ["default: " + repr(self.default)]
+        return "Argument({})".format(", ".join(args))
+
+
+class OptionGroup(object):
+
+    def __init__(self, name, description="", parser=None):
+        self.name = name
+        self.description = description
+        self.options = []
+        self.parser = parser
+
+    def addoption(self, *optnames, **attrs):
+        """ add an option to this group.
+
+        if a shortened version of a long option is specified it will
+        be suppressed in the help. addoption('--twowords', '--two-words')
+        results in help showing '--two-words' only, but --twowords gets
+        accepted **and** the automatic destination is in args.twowords
+        """
+        conflict = set(optnames).intersection(
+            name for opt in self.options for name in opt.names()
+        )
+        if conflict:
+            raise ValueError("option names %s already added" % conflict)
+        option = Argument(*optnames, **attrs)
+        self._addoption_instance(option, shortupper=False)
+
+    def _addoption(self, *optnames, **attrs):
+        option = Argument(*optnames, **attrs)
+        self._addoption_instance(option, shortupper=True)
+
+    def _addoption_instance(self, option, shortupper=False):
+        if not shortupper:
+            for opt in option._short_opts:
+                if opt[0] == "-" and opt[1].islower():
+                    raise ValueError("lowercase shortoptions reserved")
+        if self.parser:
+            self.parser.processoption(option)
+        self.options.append(option)
+
+
+class MyOptionParser(argparse.ArgumentParser):
+
+    def __init__(self, parser, extra_info=None):
+        if not extra_info:
+            extra_info = {}
+        self._parser = parser
+        argparse.ArgumentParser.__init__(
+            self,
+            usage=parser._usage,
+            add_help=False,
+            formatter_class=DropShorterLongHelpFormatter,
+        )
+        # extra_info is a dict of (param -> value) to display if there's
+        # an usage error to provide more contextual information to the user
+        self.extra_info = extra_info
+
+    def parse_args(self, args=None, namespace=None):
+        """allow splitting of positional arguments"""
+        args, argv = self.parse_known_args(args, namespace)
+        if argv:
+            for arg in argv:
+                if arg and arg[0] == "-":
+                    lines = ["unrecognized arguments: %s" % (" ".join(argv))]
+                    for k, v in sorted(self.extra_info.items()):
+                        lines.append("  %s: %s" % (k, v))
+                    self.error("\n".join(lines))
+            getattr(args, FILE_OR_DIR).extend(argv)
+        return args
+
+
+class DropShorterLongHelpFormatter(argparse.HelpFormatter):
+    """shorten help for long options that differ only in extra hyphens
+
+    - collapse **long** options that are the same except for extra hyphens
+    - special action attribute map_long_option allows surpressing additional
+      long options
+    - shortcut if there are only two options and one of them is a short one
+    - cache result on action object as this is called at least 2 times
+    """
+
+    def _format_action_invocation(self, action):
+        orgstr = argparse.HelpFormatter._format_action_invocation(self, action)
+        if orgstr and orgstr[0] != "-":  # only optional arguments
+            return orgstr
+        res = getattr(action, "_formatted_action_invocation", None)
+        if res:
+            return res
+        options = orgstr.split(", ")
+        if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):
+            # a shortcut for '-h, --help' or '--abc', '-a'
+            action._formatted_action_invocation = orgstr
+            return orgstr
+        return_list = []
+        option_map = getattr(action, "map_long_option", {})
+        if option_map is None:
+            option_map = {}
+        short_long = {}
+        for option in options:
+            if len(option) == 2 or option[2] == " ":
+                continue
+            if not option.startswith("--"):
+                raise ArgumentError(
+                    'long optional argument without "--": [%s]' % (option), self
+                )
+            xxoption = option[2:]
+            if xxoption.split()[0] not in option_map:
+                shortened = xxoption.replace("-", "")
+                if (
+                    shortened not in short_long
+                    or len(short_long[shortened]) < len(xxoption)
+                ):
+                    short_long[shortened] = xxoption
+        # now short_long has been filled out to the longest with dashes
+        # **and** we keep the right option ordering from add_argument
+        for option in options:
+            if len(option) == 2 or option[2] == " ":
+                return_list.append(option)
+            if option[2:] == short_long.get(option.replace("-", "")):
+                return_list.append(option.replace(" ", "=", 1))
+        action._formatted_action_invocation = ", ".join(return_list)
+        return action._formatted_action_invocation
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/config/exceptions.py
@@ -0,0 +1,8 @@
+class UsageError(Exception):
+    """ error in pytest usage or invocation"""
+
+
+class PrintHelp(Exception):
+    """Raised when pytest should print it's help to skip the rest of the
+    argument parsing and validation."""
+    pass
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/config/findpaths.py
@@ -0,0 +1,140 @@
+import py
+import os
+from .exceptions import UsageError
+
+
+def exists(path, ignore=EnvironmentError):
+    try:
+        return path.check()
+    except ignore:
+        return False
+
+
+def getcfg(args, warnfunc=None):
+    """
+    Search the list of arguments for a valid ini-file for pytest,
+    and return a tuple of (rootdir, inifile, cfg-dict).
+
+    note: warnfunc is an optional function used to warn
+        about ini-files that use deprecated features.
+        This parameter should be removed when pytest
+        adopts standard deprecation warnings (#1804).
+    """
+    from _pytest.deprecated import CFG_PYTEST_SECTION
+
+    inibasenames = ["pytest.ini", "tox.ini", "setup.cfg"]
+    args = [x for x in args if not str(x).startswith("-")]
+    if not args:
+        args = [py.path.local()]
+    for arg in args:
+        arg = py.path.local(arg)
+        for base in arg.parts(reverse=True):
+            for inibasename in inibasenames:
+                p = base.join(inibasename)
+                if exists(p):
+                    iniconfig = py.iniconfig.IniConfig(p)
+                    if "pytest" in iniconfig.sections:
+                        if inibasename == "setup.cfg" and warnfunc:
+                            warnfunc(
+                                "C1", CFG_PYTEST_SECTION.format(filename=inibasename)
+                            )
+                        return base, p, iniconfig["pytest"]
+                    if (
+                        inibasename == "setup.cfg"
+                        and "tool:pytest" in iniconfig.sections
+                    ):
+                        return base, p, iniconfig["tool:pytest"]
+                    elif inibasename == "pytest.ini":
+                        # allowed to be empty
+                        return base, p, {}
+    return None, None, None
+
+
+def get_common_ancestor(paths):
+    common_ancestor = None
+    for path in paths:
+        if not path.exists():
+            continue
+        if common_ancestor is None:
+            common_ancestor = path
+        else:
+            if path.relto(common_ancestor) or path == common_ancestor:
+                continue
+            elif common_ancestor.relto(path):
+                common_ancestor = path
+            else:
+                shared = path.common(common_ancestor)
+                if shared is not None:
+                    common_ancestor = shared
+    if common_ancestor is None:
+        common_ancestor = py.path.local()
+    elif common_ancestor.isfile():
+        common_ancestor = common_ancestor.dirpath()
+    return common_ancestor
+
+
+def get_dirs_from_args(args):
+
+    def is_option(x):
+        return str(x).startswith("-")
+
+    def get_file_part_from_node_id(x):
+        return str(x).split("::")[0]
+
+    def get_dir_from_path(path):
+        if path.isdir():
+            return path
+        return py.path.local(path.dirname)
+
+    # These look like paths but may not exist
+    possible_paths = (
+        py.path.local(get_file_part_from_node_id(arg))
+        for arg in args
+        if not is_option(arg)
+    )
+
+    return [get_dir_from_path(path) for path in possible_paths if path.exists()]
+
+
+def determine_setup(inifile, args, warnfunc=None, rootdir_cmd_arg=None):
+    dirs = get_dirs_from_args(args)
+    if inifile:
+        iniconfig = py.iniconfig.IniConfig(inifile)
+        is_cfg_file = str(inifile).endswith(".cfg")
+        # TODO: [pytest] section in *.cfg files is depricated. Need refactoring.
+        sections = ["tool:pytest", "pytest"] if is_cfg_file else ["pytest"]
+        for section in sections:
+            try:
+                inicfg = iniconfig[section]
+                if is_cfg_file and section == "pytest" and warnfunc:
+                    from _pytest.deprecated import CFG_PYTEST_SECTION
+
+                    warnfunc("C1", CFG_PYTEST_SECTION.format(filename=str(inifile)))
+                break
+            except KeyError:
+                inicfg = None
+        rootdir = get_common_ancestor(dirs)
+    else:
+        ancestor = get_common_ancestor(dirs)
+        rootdir, inifile, inicfg = getcfg([ancestor], warnfunc=warnfunc)
+        if rootdir is None:
+            for rootdir in ancestor.parts(reverse=True):
+                if rootdir.join("setup.py").exists():
+                    break
+            else:
+                rootdir, inifile, inicfg = getcfg(dirs, warnfunc=warnfunc)
+                if rootdir is None:
+                    rootdir = get_common_ancestor([py.path.local(), ancestor])
+                    is_fs_root = os.path.splitdrive(str(rootdir))[1] == "/"
+                    if is_fs_root:
+                        rootdir = ancestor
+    if rootdir_cmd_arg:
+        rootdir_abs_path = py.path.local(os.path.expandvars(rootdir_cmd_arg))
+        if not os.path.isdir(str(rootdir_abs_path)):
+            raise UsageError(
+                "Directory '{}' not found. Check your '--rootdir' option.".format(
+                    rootdir_abs_path
+                )
+            )
+        rootdir = rootdir_abs_path
+    return rootdir, inifile, inicfg or {}
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/debugging.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/debugging.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/debugging.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/debugging.py
@@ -1,73 +1,98 @@
 """ interactive debugging with PDB, the Python Debugger. """
 from __future__ import absolute_import, division, print_function
 import pdb
 import sys
+import os
+from doctest import UnexpectedException
+
+try:
+    from builtins import breakpoint  # noqa
+
+    SUPPORTS_BREAKPOINT_BUILTIN = True
+except ImportError:
+    SUPPORTS_BREAKPOINT_BUILTIN = False
 
 
 def pytest_addoption(parser):
     group = parser.getgroup("general")
     group._addoption(
-        '--pdb', dest="usepdb", action="store_true",
-        help="start the interactive Python debugger on errors.")
+        "--pdb",
+        dest="usepdb",
+        action="store_true",
+        help="start the interactive Python debugger on errors or KeyboardInterrupt.",
+    )
     group._addoption(
-        '--pdbcls', dest="usepdb_cls", metavar="modulename:classname",
+        "--pdbcls",
+        dest="usepdb_cls",
+        metavar="modulename:classname",
         help="start a custom interactive Python debugger on errors. "
-             "For example: --pdbcls=IPython.terminal.debugger:TerminalPdb")
+        "For example: --pdbcls=IPython.terminal.debugger:TerminalPdb",
+    )
 
 
 def pytest_configure(config):
     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
 
     if config.getvalue("usepdb"):
-        config.pluginmanager.register(PdbInvoke(), 'pdbinvoke')
+        config.pluginmanager.register(PdbInvoke(), "pdbinvoke")
+
+    # Use custom Pdb class set_trace instead of default Pdb on breakpoint() call
+    if SUPPORTS_BREAKPOINT_BUILTIN:
+        _environ_pythonbreakpoint = os.environ.get("PYTHONBREAKPOINT", "")
+        if _environ_pythonbreakpoint == "":
+            sys.breakpointhook = pytestPDB.set_trace
 
     old = (pdb.set_trace, pytestPDB._pluginmanager)
 
     def fin():
         pdb.set_trace, pytestPDB._pluginmanager = old
         pytestPDB._config = None
         pytestPDB._pdb_cls = pdb.Pdb
+        if SUPPORTS_BREAKPOINT_BUILTIN:
+            sys.breakpointhook = sys.__breakpointhook__
 
     pdb.set_trace = pytestPDB.set_trace
     pytestPDB._pluginmanager = config.pluginmanager
     pytestPDB._config = config
     pytestPDB._pdb_cls = pdb_cls
     config._cleanup.append(fin)
 
 
-class pytestPDB:
+class pytestPDB(object):
     """ Pseudo PDB that defers to the real pdb. """
     _pluginmanager = None
     _config = None
     _pdb_cls = pdb.Pdb
 
     @classmethod
     def set_trace(cls):
         """ invoke PDB set_trace debugging, dropping any IO capturing. """
         import _pytest.config
+
         frame = sys._getframe().f_back
         if cls._pluginmanager is not None:
             capman = cls._pluginmanager.getplugin("capturemanager")
             if capman:
                 capman.suspend_global_capture(in_=True)
             tw = _pytest.config.create_terminal_writer(cls._config)
             tw.line()
             tw.sep(">", "PDB set_trace (IO-capturing turned off)")
             cls._pluginmanager.hook.pytest_enter_pdb(config=cls._config)
         cls._pdb_cls().set_trace(frame)
 
 
-class PdbInvoke:
+class PdbInvoke(object):
+
     def pytest_exception_interact(self, node, call, report):
         capman = node.config.pluginmanager.getplugin("capturemanager")
         if capman:
             out, err = capman.suspend_global_capture(in_=True)
             sys.stdout.write(out)
             sys.stdout.write(err)
         _enter_pdb(node, call.excinfo, report)
 
@@ -80,44 +105,58 @@ class PdbInvoke:
 
 
 def _enter_pdb(node, excinfo, rep):
     # XXX we re-use the TerminalReporter's terminalwriter
     # because this seems to avoid some encoding related troubles
     # for not completely clear reasons.
     tw = node.config.pluginmanager.getplugin("terminalreporter")._tw
     tw.line()
+
+    showcapture = node.config.option.showcapture
+
+    for sectionname, content in (
+        ("stdout", rep.capstdout), ("stderr", rep.capstderr), ("log", rep.caplog)
+    ):
+        if showcapture in (sectionname, "all") and content:
+            tw.sep(">", "captured " + sectionname)
+            if content[-1:] == "\n":
+                content = content[:-1]
+            tw.line(content)
+
     tw.sep(">", "traceback")
     rep.toterminal(tw)
     tw.sep(">", "entering PDB")
     tb = _postmortem_traceback(excinfo)
     post_mortem(tb)
     rep._pdbshown = True
     return rep
 
 
 def _postmortem_traceback(excinfo):
-    # A doctest.UnexpectedException is not useful for post_mortem.
-    # Use the underlying exception instead:
-    from doctest import UnexpectedException
     if isinstance(excinfo.value, UnexpectedException):
+        # A doctest.UnexpectedException is not useful for post_mortem.
+        # Use the underlying exception instead:
         return excinfo.value.exc_info[2]
     else:
         return excinfo._excinfo[2]
 
 
 def _find_last_non_hidden_frame(stack):
     i = max(0, len(stack) - 1)
     while i and stack[i][0].f_locals.get("__tracebackhide__", False):
         i -= 1
     return i
 
 
 def post_mortem(t):
+
     class Pdb(pytestPDB._pdb_cls):
+
         def get_stack(self, f, t):
             stack, i = pdb.Pdb.get_stack(self, f, t)
             if f is None:
                 i = _find_last_non_hidden_frame(stack)
             return stack, i
+
     p = Pdb()
     p.reset()
     p.interaction(None, t)
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/deprecated.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/deprecated.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/deprecated.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/deprecated.py
@@ -7,46 +7,59 @@ be removed when the time comes.
 """
 from __future__ import absolute_import, division, print_function
 
 
 class RemovedInPytest4Warning(DeprecationWarning):
     """warning class for features removed in pytest 4.0"""
 
 
-MAIN_STR_ARGS = 'passing a string to pytest.main() is deprecated, ' \
-    'pass a list of arguments instead.'
+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'
+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.')
+    "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.'
+CFG_PYTEST_SECTION = "[pytest] section in {filename} 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.\n'
-    'See https://docs.pytest.org/en/latest/usage.html#creating-resultlog-format-files for more information.'
+    "--result-log is deprecated and scheduled for removal in pytest 4.0.\n"
+    "See https://docs.pytest.org/en/latest/usage.html#creating-resultlog-format-files for more information."
 )
 
 MARK_INFO_ATTRIBUTE = RemovedInPytest4Warning(
-    "MarkInfo objects are deprecated as they contain the merged marks"
+    "MarkInfo objects are deprecated as they contain merged marks which are hard to deal with correctly.\n"
+    "Please use node.get_closest_marker(name) or node.iter_markers(name).\n"
+    "Docs: https://docs.pytest.org/en/latest/mark.html#updating-code"
 )
 
 MARK_PARAMETERSET_UNPACKING = RemovedInPytest4Warning(
     "Applying marks directly to parameters is deprecated,"
     " please use pytest.param(..., marks=...) instead.\n"
     "For more details, see: https://docs.pytest.org/en/latest/parametrize.html"
 )
 
+RECORD_XML_PROPERTY = (
+    'Fixture renamed from "record_xml_property" to "record_property" as user '
+    "properties are now available to all reporters.\n"
+    '"record_xml_property" is now deprecated.'
+)
+
 COLLECTOR_MAKEITEM = RemovedInPytest4Warning(
-    "pycollector makeitem was removed "
-    "as it is an accidentially leaked internal api"
+    "pycollector makeitem was removed " "as it is an accidentially leaked internal api"
 )
 
 METAFUNC_ADD_CALL = (
     "Metafunc.addcall is deprecated and scheduled to be removed in pytest 4.0.\n"
     "Please use Metafunc.parametrize instead."
 )
+
+PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST = RemovedInPytest4Warning(
+    "Defining pytest_plugins in a non-top-level conftest is deprecated, "
+    "because it affects the entire directory tree in a non-explicit way.\n"
+    "Please move it to the top level conftest file instead."
+)
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/doctest.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/doctest.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/doctest.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/doctest.py
@@ -1,268 +1,415 @@
 """ discover and run doctests in modules and test files."""
 from __future__ import absolute_import, division, print_function
 
 import traceback
+import sys
+import platform
 
 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_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,
 )
 
+# Lazy definition of runner class
+RUNNER_CLASS = None
+
 
 def pytest_addoption(parser):
-    parser.addini('doctest_optionflags', 'option flags for doctests',
-                  type="args", default=["ELLIPSIS"])
-    parser.addini("doctest_encoding", 'encoding used for doctest files', default="utf-8")
+    parser.addini(
+        "doctest_optionflags",
+        "option flags for doctests",
+        type="args",
+        default=["ELLIPSIS"],
+    )
+    parser.addini(
+        "doctest_encoding", "encoding used for doctest files", default="utf-8"
+    )
     group = parser.getgroup("collect")
-    group.addoption("--doctest-modules",
-                    action="store_true", default=False,
-                    help="run doctests in all .py modules",
-                    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="append", default=[], metavar="pat",
-                    help="doctests file matching pattern, default: test*.txt",
-                    dest="doctestglob")
-    group.addoption("--doctest-ignore-import-errors",
-                    action="store_true", default=False,
-                    help="ignore doctest ImportErrors",
-                    dest="doctest_ignore_import_errors")
+    group.addoption(
+        "--doctest-modules",
+        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="append",
+        default=[],
+        metavar="pat",
+        help="doctests file matching pattern, default: test*.txt",
+        dest="doctestglob",
+    )
+    group.addoption(
+        "--doctest-ignore-import-errors",
+        action="store_true",
+        default=False,
+        help="ignore doctest ImportErrors",
+        dest="doctest_ignore_import_errors",
+    )
+    group.addoption(
+        "--doctest-continue-on-failure",
+        action="store_true",
+        default=False,
+        help="for a given doctest, continue to run after the first failure",
+        dest="doctest_continue_on_failure",
+    )
 
 
 def pytest_collect_file(path, parent):
     config = parent.config
     if path.ext == ".py":
         if config.option.doctestmodules and not _is_setup_py(config, path, parent):
             return DoctestModule(path, parent)
     elif _is_doctest(config, path, parent):
         return DoctestTextfile(path, parent)
 
 
 def _is_setup_py(config, path, parent):
     if path.basename != "setup.py":
         return False
     contents = path.read()
-    return 'setuptools' in contents or 'distutils' in contents
+    return "setuptools" in contents or "distutils" in contents
 
 
 def _is_doctest(config, path, parent):
-    if path.ext in ('.txt', '.rst') and parent.session.isinitpath(path):
+    if path.ext in (".txt", ".rst") and parent.session.isinitpath(path):
         return True
-    globs = config.getoption("doctestglob") or ['test*.txt']
+    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 __init__(self, reprlocation_lines):
+        # List of (reprlocation, lines) tuples
+        self.reprlocation_lines = reprlocation_lines
 
     def toterminal(self, tw):
-        for line in self.lines:
-            tw.line(line)
-        self.reprlocation.toterminal(tw)
+        for reprlocation, lines in self.reprlocation_lines:
+            for line in lines:
+                tw.line(line)
+            reprlocation.toterminal(tw)
+
+
+class MultipleDoctestFailures(Exception):
+
+    def __init__(self, failures):
+        super(MultipleDoctestFailures, self).__init__()
+        self.failures = failures
+
+
+def _init_runner_class():
+    import doctest
+
+    class PytestDoctestRunner(doctest.DebugRunner):
+        """
+        Runner to collect failures.  Note that the out variable in this case is
+        a list instead of a stdout-like object
+        """
+
+        def __init__(
+            self, checker=None, verbose=None, optionflags=0, continue_on_failure=True
+        ):
+            doctest.DebugRunner.__init__(
+                self, checker=checker, verbose=verbose, optionflags=optionflags
+            )
+            self.continue_on_failure = continue_on_failure
+
+        def report_failure(self, out, test, example, got):
+            failure = doctest.DocTestFailure(test, example, got)
+            if self.continue_on_failure:
+                out.append(failure)
+            else:
+                raise failure
+
+        def report_unexpected_exception(self, out, test, example, exc_info):
+            failure = doctest.UnexpectedException(test, example, exc_info)
+            if self.continue_on_failure:
+                out.append(failure)
+            else:
+                raise failure
+
+    return PytestDoctestRunner
+
+
+def _get_runner(checker=None, verbose=None, optionflags=0, continue_on_failure=True):
+    # We need this in order to do a lazy import on doctest
+    global RUNNER_CLASS
+    if RUNNER_CLASS is None:
+        RUNNER_CLASS = _init_runner_class()
+    return RUNNER_CLASS(
+        checker=checker,
+        verbose=verbose,
+        optionflags=optionflags,
+        continue_on_failure=continue_on_failure,
+    )
 
 
 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():
+            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)
+        self._disable_output_capturing_for_darwin()
+        failures = []
+        self.runner.run(self.dtest, out=failures)
+        if failures:
+            raise MultipleDoctestFailures(failures)
+
+    def _disable_output_capturing_for_darwin(self):
+        """
+        Disable output capturing. Otherwise, stdout is lost to doctest (#985)
+        """
+        if platform.system() != "Darwin":
+            return
+        capman = self.config.pluginmanager.getplugin("capturemanager")
+        if capman:
+            out, err = capman.suspend_global_capture(in_=True)
+            sys.stdout.write(out)
+            sys.stderr.write(err)
 
     def repr_failure(self, excinfo):
         import doctest
-        if excinfo.errisinstance((doctest.DocTestFailure,
-                                  doctest.UnexpectedException)):
-            doctestfailure = excinfo.value
-            example = doctestfailure.example
-            test = doctestfailure.test
-            filename = test.filename
-            if test.lineno is None:
-                lineno = None
-            else:
-                lineno = test.lineno + example.lineno + 1
-            message = excinfo.type.__name__
-            reprlocation = ReprFileLocation(filename, lineno, message)
-            checker = _get_checker()
-            report_choice = _get_report_choice(self.config.getoption("doctestreport"))
-            if lineno is not None:
-                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[max(example.lineno - 9, 0):example.lineno + 1]
-            else:
-                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_choice).split("\n")
-            else:
-                inner_excinfo = ExceptionInfo(excinfo.value.exc_info)
-                lines += ["UNEXPECTED EXCEPTION: %s" %
-                          repr(inner_excinfo.value)]
-                lines += traceback.format_exception(*excinfo.value.exc_info)
-            return ReprFailDoctest(reprlocation, lines)
+
+        failures = None
+        if excinfo.errisinstance((doctest.DocTestFailure, doctest.UnexpectedException)):
+            failures = [excinfo.value]
+        elif excinfo.errisinstance(MultipleDoctestFailures):
+            failures = excinfo.value.failures
+
+        if failures is not None:
+            reprlocation_lines = []
+            for failure in failures:
+                example = failure.example
+                test = failure.test
+                filename = test.filename
+                if test.lineno is None:
+                    lineno = None
+                else:
+                    lineno = test.lineno + example.lineno + 1
+                message = type(failure).__name__
+                reprlocation = ReprFileLocation(filename, lineno, message)
+                checker = _get_checker()
+                report_choice = _get_report_choice(
+                    self.config.getoption("doctestreport")
+                )
+                if lineno is not None:
+                    lines = failure.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[max(example.lineno - 9, 0):example.lineno + 1]
+                else:
+                    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 isinstance(failure, doctest.DocTestFailure):
+                    lines += checker.output_difference(
+                        example, failure.got, report_choice
+                    ).split(
+                        "\n"
+                    )
+                else:
+                    inner_excinfo = ExceptionInfo(failure.exc_info)
+                    lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)]
+                    lines += traceback.format_exception(*failure.exc_info)
+                reprlocation_lines.append((reprlocation, lines))
+            return ReprFailDoctest(reprlocation_lines)
         else:
             return super(DoctestItem, self).repr_failure(excinfo)
 
     def reportinfo(self):
         return self.fspath, self.dtest.lineno, "[doctest] %s" % self.name
 
 
 def _get_flag_lookup():
     import doctest
-    return dict(DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,
-                DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,
-                NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,
-                ELLIPSIS=doctest.ELLIPSIS,
-                IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,
-                COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,
-                ALLOW_UNICODE=_get_allow_unicode_flag(),
-                ALLOW_BYTES=_get_allow_bytes_flag(),
-                )
+
+    return dict(
+        DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,
+        DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,
+        NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,
+        ELLIPSIS=doctest.ELLIPSIS,
+        IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,
+        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")
     flag_lookup_table = _get_flag_lookup()
     flag_acc = 0
     for flag in optionflags_str:
         flag_acc |= flag_lookup_table[flag]
     return flag_acc
 
 
+def _get_continue_on_failure(config):
+    continue_on_failure = config.getvalue("doctest_continue_on_failure")
+    if continue_on_failure:
+        # We need to turn off this if we use pdb since we should stop at
+        # the first failure
+        if config.getvalue("usepdb"):
+            continue_on_failure = False
+    return continue_on_failure
+
+
 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
         encoding = self.config.getini("doctest_encoding")
         text = self.fspath.read_text(encoding)
         filename = str(self.fspath)
         name = self.fspath.basename
-        globs = {'__name__': '__main__'}
+        globs = {"__name__": "__main__"}
 
         optionflags = get_optionflags(self)
-        runner = doctest.DebugRunner(verbose=0, optionflags=optionflags,
-                                     checker=_get_checker())
+
+        runner = _get_runner(
+            verbose=0,
+            optionflags=optionflags,
+            checker=_get_checker(),
+            continue_on_failure=_get_continue_on_failure(self.config),
+        )
         _fix_spoof_python2(runner, encoding)
 
         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')
+        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.pluginmanager._importconftest(self.fspath)
         else:
             try:
                 module = self.fspath.pyimport()
             except ImportError:
-                if self.config.getvalue('doctest_ignore_import_errors'):
-                    pytest.skip('unable to import module %r' % self.fspath)
+                if self.config.getvalue("doctest_ignore_import_errors"):
+                    pytest.skip("unable to import module %r" % self.fspath)
                 else:
                     raise
         # uses internal doctest module parsing mechanism
         finder = doctest.DocTestFinder()
         optionflags = get_optionflags(self)
-        runner = doctest.DebugRunner(verbose=0, optionflags=optionflags,
-                                     checker=_get_checker())
+        runner = _get_runner(
+            verbose=0,
+            optionflags=optionflags,
+            checker=_get_checker(),
+            continue_on_failure=_get_continue_on_failure(self.config),
+        )
 
         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)
+    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'):
+    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:
@@ -270,100 +417,104 @@ def _get_checker():
 
         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)
+            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)
+                    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)
+                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')
+
+    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')
+
+    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]
+    }[
+        key
+    ]
 
 
 def _fix_spoof_python2(runner, encoding):
     """
     Installs a "SpoofOut" into the given DebugRunner so it properly deals with unicode output. This
     should patch only doctests for text files because they don't have a way to declare their
     encoding. Doctests in docstrings from Python modules don't have the same problem given that
     Python already decoded the strings.
 
     This fixes the problem related in issue #2434.
     """
     from _pytest.compat import _PY2
+
     if not _PY2:
         return
 
     from doctest import _SpoofOut
 
     class UnicodeSpoof(_SpoofOut):
 
         def getvalue(self):
             result = _SpoofOut.getvalue(self)
-            if encoding:
+            if encoding and isinstance(result, bytes):
                 result = result.decode(encoding)
             return result
 
     runner._fakeout = UnicodeSpoof()
 
 
-@pytest.fixture(scope='session')
+@pytest.fixture(scope="session")
 def doctest_namespace():
     """
-    Inject names into the doctest namespace.
+    Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.
     """
     return dict()
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/fixtures.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/fixtures.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/fixtures.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/fixtures.py
@@ -1,67 +1,88 @@
 from __future__ import absolute_import, division, print_function
 
 import functools
 import inspect
 import sys
 import warnings
-from collections import OrderedDict
+from collections import OrderedDict, deque, defaultdict
+from more_itertools import flatten
 
 import attr
 import py
 from py._code.code import FormattedExcinfo
 
 import _pytest
 from _pytest import nodes
 from _pytest._code.code import TerminalRepr
 from _pytest.compat import (
-    NOTSET, exc_clear, _format_args,
-    getfslineno, get_real_func,
-    is_generator, isclass, getimfunc,
-    getlocation, getfuncargnames,
+    NOTSET,
+    exc_clear,
+    _format_args,
+    getfslineno,
+    get_real_func,
+    is_generator,
+    isclass,
+    getimfunc,
+    getlocation,
+    getfuncargnames,
     safe_getattr,
     FuncargnamesCompatAttr,
 )
 from _pytest.outcomes import fail, TEST_OUTCOME
 
+FIXTURE_MSG = 'fixtures cannot have "pytest_funcarg__" prefix and be decorated with @pytest.fixture:\n{}'
+
+
+@attr.s(frozen=True)
+class PseudoFixtureDef(object):
+    cached_result = attr.ib()
+    scope = attr.ib()
+
 
 def pytest_sessionstart(session):
     import _pytest.python
+    import _pytest.nodes
 
-    scopename2class.update({
-        'class': _pytest.python.Class,
-        'module': _pytest.python.Module,
-        'function': _pytest.main.Item,
-        'session': _pytest.main.Session,
-    })
+    scopename2class.update(
+        {
+            "class": _pytest.python.Class,
+            "module": _pytest.python.Module,
+            "function": _pytest.nodes.Item,
+            "session": _pytest.main.Session,
+        }
+    )
     session._fixturemanager = FixtureManager(session)
 
 
 scopename2class = {}
 
 
 scope2props = dict(session=())
 scope2props["module"] = ("fspath", "module")
 scope2props["class"] = scope2props["module"] + ("cls",)
-scope2props["instance"] = scope2props["class"] + ("instance", )
+scope2props["instance"] = scope2props["class"] + ("instance",)
 scope2props["function"] = scope2props["instance"] + ("function", "keywords")
 
 
 def scopeproperty(name=None, doc=None):
+
     def decoratescope(func):
         scopename = name or func.__name__
 
         def provide(self):
             if func.__name__ in scope2props[self.scope]:
                 return func(self)
-            raise AttributeError("%s not available in %s-scoped context" % (
-                scopename, self.scope))
+            raise AttributeError(
+                "%s not available in %s-scoped context" % (scopename, self.scope)
+            )
 
         return property(provide, None, None, func.__doc__)
+
     return decoratescope
 
 
 def get_scope_node(node, scope):
     cls = scopename2class.get(scope)
     if cls is None:
         raise ValueError("unknown scope")
     return node.getparent(cls)
@@ -82,18 +103,17 @@ def add_funcarg_pseudo_fixture_def(colle
     for callspec in metafunc._calls:
         for argname, argvalue in callspec.funcargs.items():
             assert argname not in callspec.params
             callspec.params[argname] = argvalue
             arg2params_list = arg2params.setdefault(argname, [])
             callspec.indices[argname] = len(arg2params_list)
             arg2params_list.append(argvalue)
             if argname not in arg2scope:
-                scopenum = callspec._arg2scopenum.get(argname,
-                                                      scopenum_function)
+                scopenum = callspec._arg2scopenum.get(argname, scopenum_function)
                 arg2scope[argname] = scopes[scopenum]
         callspec.funcargs.clear()
 
     # register artificial FixtureDef's so that later at test execution
     # time we can rely on a proper FixtureDef to exist for fixture setup.
     arg2fixturedefs = metafunc._arg2fixturedefs
     for argname, valuelist in arg2params.items():
         # if we have a scope that is higher than function we need
@@ -106,20 +126,26 @@ def add_funcarg_pseudo_fixture_def(colle
             node = get_scope_node(collector, scope)
             if node is None:
                 assert scope == "class" and isinstance(collector, _pytest.python.Module)
                 # use module-level collector for class-scope (for now)
                 node = collector
         if node and argname in node._name2pseudofixturedef:
             arg2fixturedefs[argname] = [node._name2pseudofixturedef[argname]]
         else:
-            fixturedef = FixtureDef(fixturemanager, '', argname,
-                                    get_direct_param_fixture_func,
-                                    arg2scope[argname],
-                                    valuelist, False, False)
+            fixturedef = FixtureDef(
+                fixturemanager,
+                "",
+                argname,
+                get_direct_param_fixture_func,
+                arg2scope[argname],
+                valuelist,
+                False,
+                False,
+            )
             arg2fixturedefs[argname] = [fixturedef]
             if node is not None:
                 node._name2pseudofixturedef[argname] = fixturedef
 
 
 def getfixturemarker(obj):
     """ return fixturemarker or None if it doesn't exist or raised
     exceptions."""
@@ -141,88 +167,91 @@ def get_parametrized_fixture_keys(item, 
         pass
     else:
         # cs.indices.items() is random order of argnames.  Need to
         # sort this so that different calls to
         # get_parametrized_fixture_keys will be deterministic.
         for argname, param_index in sorted(cs.indices.items()):
             if cs._arg2scopenum[argname] != scopenum:
                 continue
-            if scopenum == 0:    # session
+            if scopenum == 0:  # session
                 key = (argname, param_index)
             elif scopenum == 1:  # module
                 key = (argname, param_index, item.fspath)
             elif scopenum == 2:  # class
                 key = (argname, param_index, item.fspath, item.cls)
             yield key
 
 
 # algorithm for sorting on a per-parametrized resource setup basis
 # it is called for scopenum==0 (session) first and performs sorting
 # down to the lower scopes such as to minimize number of "high scope"
 # setups and teardowns
 
+
 def reorder_items(items):
     argkeys_cache = {}
+    items_by_argkey = {}
     for scopenum in range(0, scopenum_function):
         argkeys_cache[scopenum] = d = {}
+        items_by_argkey[scopenum] = item_d = defaultdict(deque)
         for item in items:
             keys = OrderedDict.fromkeys(get_parametrized_fixture_keys(item, scopenum))
             if keys:
                 d[item] = keys
-    return reorder_items_atscope(items, set(), argkeys_cache, 0)
+                for key in keys:
+                    item_d[key].append(item)
+    items = OrderedDict.fromkeys(items)
+    return list(reorder_items_atscope(items, argkeys_cache, items_by_argkey, 0))
 
 
-def reorder_items_atscope(items, ignore, argkeys_cache, scopenum):
-    if scopenum >= scopenum_function or len(items) < 3:
-        return items
-    items_done = []
-    while 1:
-        items_before, items_same, items_other, newignore = \
-            slice_items(items, ignore, argkeys_cache[scopenum])
-        items_before = reorder_items_atscope(
-            items_before, ignore, argkeys_cache, scopenum + 1)
-        if items_same is None:
-            # nothing to reorder in this scope
-            assert items_other is None
-            return items_done + items_before
-        items_done.extend(items_before)
-        items = items_same + items_other
-        ignore = newignore
+def fix_cache_order(item, argkeys_cache, items_by_argkey):
+    for scopenum in range(0, scopenum_function):
+        for key in argkeys_cache[scopenum].get(item, []):
+            items_by_argkey[scopenum][key].appendleft(item)
 
 
-def slice_items(items, ignore, scoped_argkeys_cache):
-    # we pick the first item which uses a fixture instance in the
-    # requested scope and which we haven't seen yet.  We slice the input
-    # items list into a list of items_nomatch, items_same and
-    # items_other
-    if scoped_argkeys_cache:  # do we need to do work at all?
-        it = iter(items)
-        # first find a slicing key
-        for i, item in enumerate(it):
-            argkeys = scoped_argkeys_cache.get(item)
-            if argkeys is not None:
-                newargkeys = OrderedDict.fromkeys(k for k in argkeys if k not in ignore)
-                if newargkeys:  # found a slicing key
-                    slicing_argkey, _ = newargkeys.popitem()
-                    items_before = items[:i]
-                    items_same = [item]
-                    items_other = []
-                    # now slice the remainder of the list
-                    for item in it:
-                        argkeys = scoped_argkeys_cache.get(item)
-                        if argkeys and slicing_argkey in argkeys and \
-                                slicing_argkey not in ignore:
-                            items_same.append(item)
-                        else:
-                            items_other.append(item)
-                    newignore = ignore.copy()
-                    newignore.add(slicing_argkey)
-                    return (items_before, items_same, items_other, newignore)
-    return items, None, None, None
+def reorder_items_atscope(items, argkeys_cache, items_by_argkey, scopenum):
+    if scopenum >= scopenum_function or len(items) < 3:
+        return items
+    ignore = set()
+    items_deque = deque(items)
+    items_done = OrderedDict()
+    scoped_items_by_argkey = items_by_argkey[scopenum]
+    scoped_argkeys_cache = argkeys_cache[scopenum]
+    while items_deque:
+        no_argkey_group = OrderedDict()
+        slicing_argkey = None
+        while items_deque:
+            item = items_deque.popleft()
+            if item in items_done or item in no_argkey_group:
+                continue
+            argkeys = OrderedDict.fromkeys(
+                k for k in scoped_argkeys_cache.get(item, []) if k not in ignore
+            )
+            if not argkeys:
+                no_argkey_group[item] = None
+            else:
+                slicing_argkey, _ = argkeys.popitem()
+                # we don't have to remove relevant items from later in the deque because they'll just be ignored
+                matching_items = [
+                    i for i in scoped_items_by_argkey[slicing_argkey] if i in items
+                ]
+                for i in reversed(matching_items):
+                    fix_cache_order(i, argkeys_cache, items_by_argkey)
+                    items_deque.appendleft(i)
+                break
+        if no_argkey_group:
+            no_argkey_group = reorder_items_atscope(
+                no_argkey_group, argkeys_cache, items_by_argkey, scopenum + 1
+            )
+            for item in no_argkey_group:
+                items_done[item] = None
+        ignore.add(slicing_argkey)
+    return items_done
 
 
 def fillfixtures(function):
     """ fill missing funcargs for a test function. """
     try:
         request = function._request
     except AttributeError:
         # XXX this special code path is only expected to execute
@@ -241,17 +270,18 @@ def fillfixtures(function):
     else:
         request._fillfixtures()
 
 
 def get_direct_param_fixture_func(request):
     return request.param
 
 
-class FuncFixtureInfo:
+class FuncFixtureInfo(object):
+
     def __init__(self, argnames, names_closure, name2fixturedefs):
         self.argnames = argnames
         self.names_closure = names_closure
         self.name2fixturedefs = name2fixturedefs
 
 
 class FixtureRequest(FuncargnamesCompatAttr):
     """ A request for a fixture from a test or fixture function.
@@ -262,17 +292,16 @@ class FixtureRequest(FuncargnamesCompatA
     """
 
     def __init__(self, pyfuncitem):
         self._pyfuncitem = pyfuncitem
         #: fixture for which this request is being performed
         self.fixturename = None
         #: Scope string, one of "function", "class", "module", "session"
         self.scope = "function"
-        self._fixture_values = {}  # argname -> fixture value
         self._fixture_defs = {}  # argname -> FixtureDef
         fixtureinfo = pyfuncitem._fixtureinfo
         self._arg2fixturedefs = fixtureinfo.name2fixturedefs.copy()
         self._arg2index = {}
         self._fixturemanager = pyfuncitem.session._fixturemanager
 
     @property
     def fixturenames(self):
@@ -282,17 +311,17 @@ class FixtureRequest(FuncargnamesCompatA
     @property
     def node(self):
         """ underlying collection node (depends on current request scope)"""
         return self._getscopeitem(self.scope)
 
     def _getnextfixturedef(self, argname):
         fixturedefs = self._arg2fixturedefs.get(argname, None)
         if fixturedefs is None:
-            # we arrive here because of a  a dynamic call to
+            # we arrive here because of a dynamic call to
             # getfixturevalue(argname) usage which was naturally
             # not known at parsing/collection time
             parentid = self._pyfuncitem.parent.nodeid
             fixturedefs = self._fixturemanager.getfixturedefs(argname, parentid)
             self._arg2fixturedefs[argname] = fixturedefs
         # fixturedefs list is immutable so we maintain a decreasing index
         index = self._arg2index.get(argname, 0) - 1
         if fixturedefs is None or (-index > len(fixturedefs)):
@@ -320,18 +349,17 @@ class FixtureRequest(FuncargnamesCompatA
     @property
     def instance(self):
         """ instance (can be None) on which test function was collected. """
         # unittest support hack, see _pytest.unittest.TestCaseFunction
         try:
             return self._pyfuncitem._testcase
         except AttributeError:
             function = getattr(self, "function", None)
-            if function is not None:
-                return py.builtin._getimself(function)
+            return getattr(function, "__self__", None)
 
     @scopeproperty()
     def module(self):
         """ python module object where the test function was collected. """
         return self._pyfuncitem.getparent(_pytest.python.Module).obj
 
     @scopeproperty()
     def fspath(self):
@@ -353,30 +381,28 @@ class FixtureRequest(FuncargnamesCompatA
         last test within the requesting test context finished
         execution. """
         # XXX usually this method is shadowed by fixturedef specific ones
         self._addfinalizer(finalizer, scope=self.scope)
 
     def _addfinalizer(self, finalizer, scope):
         colitem = self._getscopeitem(scope)
         self._pyfuncitem.session._setupstate.addfinalizer(
-            finalizer=finalizer, colitem=colitem)
+            finalizer=finalizer, colitem=colitem
+        )
 
     def applymarker(self, marker):
         """ Apply a marker to a single test function invocation.
         This method is useful if you don't want to have a keyword/marker
         on all function invocations.
 
         :arg marker: a :py:class:`_pytest.mark.MarkDecorator` object
             created by a call to ``pytest.mark.NAME(...)``.
         """
-        try:
-            self.node.keywords[marker.markname] = marker
-        except AttributeError:
-            raise ValueError(marker)
+        self.node.add_marker(marker)
 
     def raiseerror(self, msg):
         """ raise a FixtureLookupError with the given message. """
         raise self._fixturemanager.FixtureLookupError(None, self, msg)
 
     def _fillfixtures(self):
         item = self._pyfuncitem
         fixturenames = getattr(item, "fixturenames", self.fixturenames)
@@ -394,84 +420,89 @@ class FixtureRequest(FuncargnamesCompatA
         ``request.addfinalizer()``.
 
         :arg teardown: function receiving a previously setup resource.
         :arg setup: a no-argument function creating a resource.
         :arg scope: a string value out of ``function``, ``class``, ``module``
             or ``session`` indicating the caching lifecycle of the resource.
         :arg extrakey: added to internal caching key of (funcargname, scope).
         """
-        if not hasattr(self.config, '_setupcache'):
+        if not hasattr(self.config, "_setupcache"):
             self.config._setupcache = {}  # XXX weakref?
         cachekey = (self.fixturename, self._getscopeitem(scope), extrakey)
         cache = self.config._setupcache
         try:
             val = cache[cachekey]
         except KeyError:
             self._check_scope(self.fixturename, self.scope, scope)
             val = setup()
             cache[cachekey] = val
             if teardown is not None:
+
                 def finalizer():
                     del cache[cachekey]
                     teardown(val)
+
                 self._addfinalizer(finalizer, scope=scope)
         return val
 
     def getfixturevalue(self, argname):
         """ Dynamically run a named fixture function.
 
         Declaring fixtures via function argument is recommended where possible.
         But if you can only decide whether to use another fixture at test
         setup time, you may use this function to retrieve it inside a fixture
         or test function body.
         """
         return self._get_active_fixturedef(argname).cached_result[0]
 
     def getfuncargvalue(self, argname):
         """ Deprecated, use getfixturevalue. """
         from _pytest import deprecated
-        warnings.warn(
-            deprecated.GETFUNCARGVALUE,
-            DeprecationWarning,
-            stacklevel=2)
+
+        warnings.warn(deprecated.GETFUNCARGVALUE, DeprecationWarning, stacklevel=2)
         return self.getfixturevalue(argname)
 
     def _get_active_fixturedef(self, argname):
         try:
             return self._fixture_defs[argname]
         except KeyError:
             try:
                 fixturedef = self._getnextfixturedef(argname)
             except FixtureLookupError:
                 if argname == "request":
-                    class PseudoFixtureDef:
-                        cached_result = (self, [0], None)
-                        scope = "function"
-                    return PseudoFixtureDef
+                    cached_result = (self, [0], None)
+                    scope = "function"
+                    return PseudoFixtureDef(cached_result, scope)
                 raise
         # remove indent to prevent the python3 exception
         # from leaking into the call
-        result = self._getfixturevalue(fixturedef)
-        self._fixture_values[argname] = result
+        self._compute_fixture_value(fixturedef)
         self._fixture_defs[argname] = fixturedef
         return fixturedef
 
     def _get_fixturestack(self):
         current = self
         values = []
         while 1:
             fixturedef = getattr(current, "_fixturedef", None)
             if fixturedef is None:
                 values.reverse()
                 return values
             values.append(fixturedef)
             current = current._parent_request
 
-    def _getfixturevalue(self, fixturedef):
+    def _compute_fixture_value(self, fixturedef):
+        """
+        Creates a SubRequest based on "self" and calls the execute method of the given fixturedef object. This will
+        force the FixtureDef object to throw away any previous results and compute a new fixture value, which
+        will be stored into the FixtureDef object itself.
+
+        :param FixtureDef fixturedef:
+        """
         # prepare a subrequest object before calling fixture function
         # (latter managed by fixturedef)
         argname = fixturedef.argname
         funcitem = self._pyfuncitem
         scope = fixturedef.scope
         try:
             param = funcitem.callspec.getparam(argname)
         except (AttributeError, ValueError):
@@ -482,18 +513,18 @@ class FixtureRequest(FuncargnamesCompatA
                 frameinfo = inspect.getframeinfo(frame[0])
                 source_path = frameinfo.filename
                 source_lineno = frameinfo.lineno
                 source_path = py.path.local(source_path)
                 if source_path.relto(funcitem.config.rootdir):
                     source_path = source_path.relto(funcitem.config.rootdir)
                 msg = (
                     "The requested fixture has no parameter defined for the "
-                    "current test.\n\nRequested fixture '{0}' defined in:\n{1}"
-                    "\n\nRequested here:\n{2}:{3}".format(
+                    "current test.\n\nRequested fixture '{}' defined in:\n{}"
+                    "\n\nRequested here:\n{}:{}".format(
                         fixturedef.argname,
                         getlocation(fixturedef.func, funcitem.config.rootdir),
                         source_path,
                         source_lineno,
                     )
                 )
                 fail(msg)
         else:
@@ -510,55 +541,59 @@ class FixtureRequest(FuncargnamesCompatA
         # check if a higher-level scoped fixture accesses a lower level one
         subrequest._check_scope(argname, self.scope, scope)
 
         # clear sys.exc_info before invoking the fixture (python bug?)
         # if its not explicitly cleared it will leak into the call
         exc_clear()
         try:
             # call the fixture function
-            val = fixturedef.execute(request=subrequest)
+            fixturedef.execute(request=subrequest)
         finally:
             # if fixture function failed it might have registered finalizers
-            self.session._setupstate.addfinalizer(functools.partial(fixturedef.finish, request=subrequest),
-                                                  subrequest.node)
-        return val
+            self.session._setupstate.addfinalizer(
+                functools.partial(fixturedef.finish, request=subrequest),
+                subrequest.node,
+            )
 
     def _check_scope(self, argname, invoking_scope, requested_scope):
         if argname == "request":
             return
         if scopemismatch(invoking_scope, requested_scope):
             # try to report something helpful
             lines = self._factorytraceback()
-            fail("ScopeMismatch: You tried to access the %r scoped "
-                 "fixture %r with a %r scoped request object, "
-                 "involved factories\n%s" % (
-                     (requested_scope, argname, invoking_scope, "\n".join(lines))),
-                 pytrace=False)
+            fail(
+                "ScopeMismatch: You tried to access the %r scoped "
+                "fixture %r with a %r scoped request object, "
+                "involved factories\n%s"
+                % ((requested_scope, argname, invoking_scope, "\n".join(lines))),
+                pytrace=False,
+            )
 
     def _factorytraceback(self):
         lines = []
         for fixturedef in self._get_fixturestack():
             factory = fixturedef.func
             fs, lineno = getfslineno(factory)
             p = self._pyfuncitem.session.fspath.bestrelpath(fs)
             args = _format_args(factory)
-            lines.append("%s:%d:  def %s%s" % (
-                p, lineno, factory.__name__, args))
+            lines.append("%s:%d:  def %s%s" % (p, lineno, factory.__name__, args))
         return lines
 
     def _getscopeitem(self, scope):
         if scope == "function":
             # this might also be a non-function Item despite its attribute name
             return self._pyfuncitem
         node = get_scope_node(self._pyfuncitem, scope)
         if node is None and scope == "class":
             # fallback to function item itself
             node = self._pyfuncitem
-        assert node, 'Could not obtain a node for scope "{}" for function {!r}'.format(scope, self._pyfuncitem)
+        assert node, 'Could not obtain a node for scope "{}" for function {!r}'.format(
+            scope, self._pyfuncitem
+        )
         return node
 
     def __repr__(self):
         return "<FixtureRequest for %r>" % (self.node)
 
 
 class SubRequest(FixtureRequest):
     """ a sub request for handling getting a fixture from a
@@ -568,17 +603,16 @@ class SubRequest(FixtureRequest):
         self._parent_request = request
         self.fixturename = fixturedef.argname
         if param is not NOTSET:
             self.param = param
         self.param_index = param_index
         self.scope = scope
         self._fixturedef = fixturedef
         self._pyfuncitem = request._pyfuncitem
-        self._fixture_values = request._fixture_values
         self._fixture_defs = request._fixture_defs
         self._arg2fixturedefs = request._arg2fixturedefs
         self._arg2index = request._arg2index
         self._fixturemanager = request._fixturemanager
 
     def __repr__(self):
         return "<SubRequest %r for %r>" % (self.fixturename, self._pyfuncitem)
 
@@ -603,19 +637,19 @@ def scopemismatch(currentscope, newscope
 def scope2index(scope, descr, where=None):
     """Look up the index of ``scope`` and raise a descriptive value error
     if not defined.
     """
     try:
         return scopes.index(scope)
     except ValueError:
         raise ValueError(
-            "{0} {1}has an unsupported scope value '{2}'".format(
-                descr, 'from {0} '.format(where) if where else '',
-                scope)
+            "{} {}has an unsupported scope value '{}'".format(
+                descr, "from {} ".format(where) if where else "", scope
+            )
         )
 
 
 class FixtureLookupError(LookupError):
     """ could not return a requested Fixture (missing or invalid). """
 
     def __init__(self, argname, request, msg=None):
         self.argname = argname
@@ -640,17 +674,17 @@ class FixtureLookupError(LookupError):
             except (IOError, IndexError, TypeError):
                 error_msg = "file %s, line %s: source code not available"
                 addline(error_msg % (fspath, lineno + 1))
             else:
                 addline("file %s, line %s" % (fspath, lineno + 1))
                 for i, line in enumerate(lines):
                     line = line.rstrip()
                     addline("  " + line)
-                    if line.lstrip().startswith('def'):
+                    if line.lstrip().startswith("def"):
                         break
 
         if msg is None:
             fm = self.request._fixturemanager
             available = []
             parentid = self.request._pyfuncitem.parent.nodeid
             for name, fixturedefs in fm._arg2fixturedefs.items():
                 faclist = list(fm._matchfactories(fixturedefs, parentid))
@@ -659,82 +693,94 @@ class FixtureLookupError(LookupError):
             msg = "fixture %r not found" % (self.argname,)
             msg += "\n available fixtures: %s" % (", ".join(sorted(available)),)
             msg += "\n use 'pytest --fixtures [testpath]' for help on them."
 
         return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)
 
 
 class FixtureLookupErrorRepr(TerminalRepr):
+
     def __init__(self, filename, firstlineno, tblines, errorstring, argname):
         self.tblines = tblines
         self.errorstring = errorstring
         self.filename = filename
         self.firstlineno = firstlineno
         self.argname = argname
 
     def toterminal(self, tw):
         # tw.line("FixtureLookupError: %s" %(self.argname), red=True)
         for tbline in self.tblines:
             tw.line(tbline.rstrip())
         lines = self.errorstring.split("\n")
         if lines:
-            tw.line('{0}       {1}'.format(FormattedExcinfo.fail_marker,
-                                           lines[0].strip()), red=True)
+            tw.line(
+                "{}       {}".format(FormattedExcinfo.fail_marker, lines[0].strip()),
+                red=True,
+            )
             for line in lines[1:]:
-                tw.line('{0}       {1}'.format(FormattedExcinfo.flow_marker,
-                                               line.strip()), red=True)
+                tw.line(
+                    "{}       {}".format(FormattedExcinfo.flow_marker, line.strip()),
+                    red=True,
+                )
         tw.line()
         tw.line("%s:%d" % (self.filename, self.firstlineno + 1))
 
 
 def fail_fixturefunc(fixturefunc, msg):
     fs, lineno = getfslineno(fixturefunc)
     location = "%s:%s" % (fs, lineno + 1)
     source = _pytest._code.Source(fixturefunc)
-    fail(msg + ":\n\n" + str(source.indent()) + "\n" + location,
-         pytrace=False)
+    fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, pytrace=False)
 
 
 def call_fixture_func(fixturefunc, request, kwargs):
     yieldctx = is_generator(fixturefunc)
     if yieldctx:
         it = fixturefunc(**kwargs)
         res = next(it)
 
         def teardown():
             try:
                 next(it)
             except StopIteration:
                 pass
             else:
-                fail_fixturefunc(fixturefunc,
-                                 "yield_fixture function has more than one 'yield'")
+                fail_fixturefunc(
+                    fixturefunc, "yield_fixture function has more than one 'yield'"
+                )
 
         request.addfinalizer(teardown)
     else:
         res = fixturefunc(**kwargs)
     return res
 
 
-class FixtureDef:
+class FixtureDef(object):
     """ A container for a factory definition. """
 
-    def __init__(self, fixturemanager, baseid, argname, func, scope, params,
-                 unittest=False, ids=None):
+    def __init__(
+        self,
+        fixturemanager,
+        baseid,
+        argname,
+        func,
+        scope,
+        params,
+        unittest=False,
+        ids=None,
+    ):
         self._fixturemanager = fixturemanager
-        self.baseid = baseid or ''
+        self.baseid = baseid or ""
         self.has_location = baseid is not None
         self.func = func
         self.argname = argname
         self.scope = scope
         self.scopenum = scope2index(
-            scope or "function",
-            descr='fixture {0}'.format(func.__name__),
-            where=baseid
+            scope or "function", descr="fixture {}".format(func.__name__), where=baseid
         )
         self.params = params
         self.argnames = getfuncargnames(func, is_method=unittest)
         self.unittest = unittest
         self.ids = ids
         self._finalizers = []
 
     def addfinalizer(self, finalizer):
@@ -786,18 +832,20 @@ class FixtureDef:
             # so we need to tear it down before creating a new one
             self.finish(request)
             assert not hasattr(self, "cached_result")
 
         hook = self._fixturemanager.session.gethookproxy(request.node.fspath)
         return hook.pytest_fixture_setup(fixturedef=self, request=request)
 
     def __repr__(self):
-        return ("<FixtureDef name=%r scope=%r baseid=%r >" %
-                (self.argname, self.scope, self.baseid))
+        return (
+            "<FixtureDef name=%r scope=%r baseid=%r >"
+            % (self.argname, self.scope, self.baseid)
+        )
 
 
 def pytest_fixture_setup(fixturedef, request):
     """ Execution of fixture setup. """
     kwargs = {}
     for argname in fixturedef.argnames:
         fixdef = request._get_active_fixturedef(argname)
         result, arg_cache_key, exc = fixdef.cached_result
@@ -833,31 +881,36 @@ def _ensure_immutable_ids(ids):
     if callable(ids):
         return ids
     return tuple(ids)
 
 
 @attr.s(frozen=True)
 class FixtureFunctionMarker(object):
     scope = attr.ib()
-    params = attr.ib(convert=attr.converters.optional(tuple))
+    params = attr.ib(converter=attr.converters.optional(tuple))
     autouse = attr.ib(default=False)
-    ids = attr.ib(default=None, convert=_ensure_immutable_ids)
+    ids = attr.ib(default=None, converter=_ensure_immutable_ids)
     name = attr.ib(default=None)
 
     def __call__(self, function):
         if isclass(function):
+            raise ValueError("class fixtures not supported (may be in the future)")
+
+        if getattr(function, "_pytestfixturefunction", False):
             raise ValueError(
-                "class fixtures not supported (may be in the future)")
+                "fixture is being applied more than once to the same function"
+            )
+
         function._pytestfixturefunction = self
         return function
 
 
 def fixture(scope="function", params=None, autouse=False, ids=None, name=None):
-    """ (return a) decorator to mark a fixture factory function.
+    """Decorator to mark a fixture factory function.
 
     This decorator can be used (with or without parameters) to define a
     fixture function.  The name of the fixture function can later be
     referenced to cause its invocation ahead of running tests: test
     modules or classes can use the pytest.mark.usefixtures(fixturename)
     marker.  Test functions can directly use fixture names as input
     arguments in which case the fixture instance returned from the fixture
     function will be injected.
@@ -886,47 +939,55 @@ def fixture(scope="function", params=Non
                 ``@pytest.fixture(name='<fixturename>')``.
 
     Fixtures can optionally provide their values to test functions using a ``yield`` statement,
     instead of ``return``. In this case, the code block after the ``yield`` statement is executed
     as teardown code regardless of the test outcome. A fixture function must yield exactly once.
     """
     if callable(scope) and params is None and autouse is False:
         # direct decoration
-        return FixtureFunctionMarker(
-            "function", params, autouse, name=name)(scope)
+        return FixtureFunctionMarker("function", params, autouse, name=name)(scope)
     if params is not None and not isinstance(params, (list, tuple)):
         params = list(params)
     return FixtureFunctionMarker(scope, params, autouse, ids=ids, name=name)
 
 
 def yield_fixture(scope="function", params=None, autouse=False, ids=None, name=None):
     """ (return a) decorator to mark a yield-fixture factory function.
 
     .. deprecated:: 3.0
         Use :py:func:`pytest.fixture` directly instead.
     """
     if callable(scope) and params is None and not autouse:
         # direct decoration
-        return FixtureFunctionMarker(
-            "function", params, autouse, ids=ids, name=name)(scope)
+        return FixtureFunctionMarker("function", params, autouse, ids=ids, name=name)(
+            scope
+        )
     else:
         return FixtureFunctionMarker(scope, params, autouse, ids=ids, name=name)
 
 
 defaultfuncargprefixmarker = fixture()
 
 
 @fixture(scope="session")
 def pytestconfig(request):
-    """ the pytest config object with access to command line opts."""
+    """Session-scoped fixture that returns the :class:`_pytest.config.Config` object.
+
+    Example::
+
+        def test_foo(pytestconfig):
+            if pytestconfig.getoption("verbose"):
+                ...
+
+    """
     return request.config
 
 
-class FixtureManager:
+class FixtureManager(object):
     """
     pytest fixtures definitions and information is stored and managed
     from this class.
 
     During collection fm.parsefactories() is called multiple times to parse
     fixture function definitions into FixtureDef objects and internal
     data structures.
 
@@ -962,27 +1023,27 @@ class FixtureManager:
         self.config = session.config
         self._arg2fixturedefs = {}
         self._holderobjseen = set()
         self._arg2finish = {}
         self._nodeid_and_autousenames = [("", self.config.getini("usefixtures"))]
         session.config.pluginmanager.register(self, "funcmanage")
 
     def getfixtureinfo(self, node, func, cls, funcargs=True):
-        if funcargs and not hasattr(node, "nofuncargs"):
+        if funcargs and not getattr(node, "nofuncargs", False):
             argnames = getfuncargnames(func, cls=cls)
         else:
             argnames = ()
-        usefixtures = getattr(func, "usefixtures", None)
+        usefixtures = flatten(
+            mark.args for mark in node.iter_markers(name="usefixtures")
+        )
         initialnames = argnames
-        if usefixtures is not None:
-            initialnames = usefixtures.args + initialnames
+        initialnames = tuple(usefixtures) + initialnames
         fm = node.session._fixturemanager
-        names_closure, arg2fixturedefs = fm.getfixtureclosure(initialnames,
-                                                              node)
+        names_closure, arg2fixturedefs = fm.getfixtureclosure(initialnames, node)
         return FuncFixtureInfo(argnames, names_closure, arg2fixturedefs)
 
     def pytest_plugin_registered(self, plugin):
         nodeid = None
         try:
             p = py.path.local(plugin.__file__)
         except AttributeError:
             pass
@@ -1002,25 +1063,22 @@ class FixtureManager:
         for baseid, basenames in self._nodeid_and_autousenames:
             if nodeid.startswith(baseid):
                 if baseid:
                     i = len(baseid)
                     nextchar = nodeid[i:i + 1]
                     if nextchar and nextchar not in ":/":
                         continue
                 autousenames.extend(basenames)
-        # make sure autousenames are sorted by scope, scopenum 0 is session
-        autousenames.sort(
-            key=lambda x: self._arg2fixturedefs[x][-1].scopenum)
         return autousenames
 
     def getfixtureclosure(self, fixturenames, parentnode):
         # collect the closure of all fixtures , starting with the given
         # fixturenames as the initial set.  As we have to visit all
-        # factory definitions anyway, we also return a arg2fixturedefs
+        # factory definitions anyway, we also return an arg2fixturedefs
         # mapping so that the caller can reuse it and does not have
         # to re-discover fixturedefs again for each fixturename
         # (discovering matching fixtures for a given name/node is expensive)
 
         parentid = parentnode.nodeid
         fixturenames_closure = self._getautousenames(parentid)
 
         def merge(otherlist):
@@ -1035,38 +1093,54 @@ class FixtureManager:
             lastlen = len(fixturenames_closure)
             for argname in fixturenames_closure:
                 if argname in arg2fixturedefs:
                     continue
                 fixturedefs = self.getfixturedefs(argname, parentid)
                 if fixturedefs:
                     arg2fixturedefs[argname] = fixturedefs
                     merge(fixturedefs[-1].argnames)
+
+        def sort_by_scope(arg_name):
+            try:
+                fixturedefs = arg2fixturedefs[arg_name]
+            except KeyError:
+                return scopes.index("function")
+            else:
+                return fixturedefs[-1].scopenum
+
+        fixturenames_closure.sort(key=sort_by_scope)
         return fixturenames_closure, arg2fixturedefs
 
     def pytest_generate_tests(self, metafunc):
         for argname in metafunc.fixturenames:
             faclist = metafunc._arg2fixturedefs.get(argname)
             if faclist:
                 fixturedef = faclist[-1]
                 if fixturedef.params is not None:
-                    parametrize_func = getattr(metafunc.function, 'parametrize', None)
-                    func_params = getattr(parametrize_func, 'args', [[None]])
-                    func_kwargs = getattr(parametrize_func, 'kwargs', {})
+                    parametrize_func = getattr(metafunc.function, "parametrize", None)
+                    if parametrize_func is not None:
+                        parametrize_func = parametrize_func.combined
+                    func_params = getattr(parametrize_func, "args", [[None]])
+                    func_kwargs = getattr(parametrize_func, "kwargs", {})
                     # skip directly parametrized arguments
                     if "argnames" in func_kwargs:
                         argnames = parametrize_func.kwargs["argnames"]
                     else:
                         argnames = func_params[0]
                     if not isinstance(argnames, (tuple, list)):
                         argnames = [x.strip() for x in argnames.split(",") if x.strip()]
                     if argname not in func_params and argname not in argnames:
-                        metafunc.parametrize(argname, fixturedef.params,
-                                             indirect=True, scope=fixturedef.scope,
-                                             ids=fixturedef.ids)
+                        metafunc.parametrize(
+                            argname,
+                            fixturedef.params,
+                            indirect=True,
+                            scope=fixturedef.scope,
+                            ids=fixturedef.ids,
+                        )
             else:
                 continue  # will raise FixtureLookupError at setup time
 
     def pytest_collection_modifyitems(self, items):
         # separate parametrized setups
         items[:] = reorder_items(items)
 
     def parsefactories(self, node_or_obj, nodeid=NOTSET, unittest=False):
@@ -1088,48 +1162,56 @@ class FixtureManager:
             marker = getfixturemarker(obj)
             if marker is None:
                 if not name.startswith(self._argprefix):
                     continue
                 if not callable(obj):
                     continue
                 marker = defaultfuncargprefixmarker
                 from _pytest import deprecated
-                self.config.warn('C1', deprecated.FUNCARG_PREFIX.format(name=name), nodeid=nodeid)
+
+                self.config.warn(
+                    "C1", deprecated.FUNCARG_PREFIX.format(name=name), nodeid=nodeid
+                )
                 name = name[len(self._argprefix):]
             elif not isinstance(marker, FixtureFunctionMarker):
                 # magic globals  with __getattr__ might have got us a wrong
                 # fixture attribute
                 continue
             else:
                 if marker.name:
                     name = marker.name
-                msg = 'fixtures cannot have "pytest_funcarg__" prefix ' \
-                      'and be decorated with @pytest.fixture:\n%s' % name
-                assert not name.startswith(self._argprefix), msg
+                assert not name.startswith(self._argprefix), FIXTURE_MSG.format(name)
 
-            fixture_def = FixtureDef(self, nodeid, name, obj,
-                                     marker.scope, marker.params,
-                                     unittest=unittest, ids=marker.ids)
+            fixture_def = FixtureDef(
+                self,
+                nodeid,
+                name,
+                obj,
+                marker.scope,
+                marker.params,
+                unittest=unittest,
+                ids=marker.ids,
+            )
 
             faclist = self._arg2fixturedefs.setdefault(name, [])
             if fixture_def.has_location:
                 faclist.append(fixture_def)
             else:
                 # fixturedefs with no location are at the front
                 # so this inserts the current fixturedef after the
                 # existing fixturedefs from external plugins but
                 # before the fixturedefs provided in conftests.
                 i = len([f for f in faclist if not f.has_location])
                 faclist.insert(i, fixture_def)
             if marker.autouse:
                 autousenames.append(name)
 
         if autousenames:
-            self._nodeid_and_autousenames.append((nodeid or '', autousenames))
+            self._nodeid_and_autousenames.append((nodeid or "", autousenames))
 
     def getfixturedefs(self, argname, nodeid):
         """
         Gets a list of fixtures which are applicable to the given node id.
 
         :param str argname: name of the fixture to search for
         :param str nodeid: full node id of the requesting test.
         :return: list[FixtureDef]
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/freeze_support.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/freeze_support.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/freeze_support.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/freeze_support.py
@@ -2,42 +2,44 @@
 Provides a function to report all internal modules for using freezing tools
 pytest
 """
 from __future__ import absolute_import, division, print_function
 
 
 def freeze_includes():
     """
-    Returns a list of module names used by py.test that should be
+    Returns a list of module names used by pytest 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=''):
+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__ + '.'
+        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 + '.'):
+            for m in _iter_all_modules(os.path.join(path, name), prefix=name + "."):
                 yield prefix + m
         else:
             yield prefix + name
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/helpconfig.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/helpconfig.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/helpconfig.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/helpconfig.py
@@ -13,172 +13,200 @@ class HelpAction(Action):
     """This is an argparse Action that will raise an exception in
     order to skip the rest of the argument parsing when --help is passed.
     This prevents argparse from quitting due to missing required arguments
     when any are defined, for example by ``pytest_addoption``.
     This is similar to the way that the builtin argparse --help option is
     implemented by raising SystemExit.
     """
 
-    def __init__(self,
-                 option_strings,
-                 dest=None,
-                 default=False,
-                 help=None):
+    def __init__(self, option_strings, dest=None, default=False, help=None):
         super(HelpAction, self).__init__(
             option_strings=option_strings,
             dest=dest,
             const=True,
             default=default,
             nargs=0,
-            help=help)
+            help=help,
+        )
 
     def __call__(self, parser, namespace, values, option_string=None):
         setattr(namespace, self.dest, self.const)
 
         # We should only skip the rest of the parsing after preparse is done
-        if getattr(parser._parser, 'after_preparse', False):
+        if getattr(parser._parser, "after_preparse", False):
             raise PrintHelp
 
 
 def pytest_addoption(parser):
-    group = parser.getgroup('debugconfig')
-    group.addoption('--version', action="store_true",
-                    help="display pytest lib version and import information.")
-    group._addoption("-h", "--help", action=HelpAction, dest="help",
-                     help="show help message and configuration info")
-    group._addoption('-p', action="append", dest="plugins", default=[],
-                     metavar="name",
-                     help="early-load given plugin (multi-allowed). "
-                     "To avoid loading of plugins, use the `no:` prefix, e.g. "
-                     "`no:doctest`.")
-    group.addoption('--traceconfig', '--trace-config',
-                    action="store_true", default=False,
-                    help="trace considerations of conftest.py files."),
-    group.addoption('--debug',
-                    action="store_true", dest="debug", default=False,
-                    help="store internal tracing debug information in 'pytestdebug.log'.")
+    group = parser.getgroup("debugconfig")
+    group.addoption(
+        "--version",
+        action="store_true",
+        help="display pytest lib version and import information.",
+    )
+    group._addoption(
+        "-h",
+        "--help",
+        action=HelpAction,
+        dest="help",
+        help="show help message and configuration info",
+    )
     group._addoption(
-        '-o', '--override-ini', nargs='*', dest="override_ini",
+        "-p",
         action="append",
-        help="override config option with option=value style, e.g. `-o xfail_strict=True`.")
+        dest="plugins",
+        default=[],
+        metavar="name",
+        help="early-load given plugin (multi-allowed). "
+        "To avoid loading of plugins, use the `no:` prefix, e.g. "
+        "`no:doctest`.",
+    )
+    group.addoption(
+        "--traceconfig",
+        "--trace-config",
+        action="store_true",
+        default=False,
+        help="trace considerations of conftest.py files.",
+    ),
+    group.addoption(
+        "--debug",
+        action="store_true",
+        dest="debug",
+        default=False,
+        help="store internal tracing debug information in 'pytestdebug.log'.",
+    )
+    group._addoption(
+        "-o",
+        "--override-ini",
+        dest="override_ini",
+        action="append",
+        help='override ini option with "option=value" style, e.g. `-o xfail_strict=True -o cache_dir=cache`.',
+    )
 
 
 @pytest.hookimpl(hookwrapper=True)
 def pytest_cmdline_parse():
     outcome = yield
     config = outcome.get_result()
     if config.option.debug:
         path = os.path.abspath("pytestdebug.log")
-        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))
+        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.trace.root.setwriter(debugfile.write)
         undo_tracing = config.pluginmanager.enable_tracing()
         sys.stderr.write("writing pytestdebug information to %s\n" % path)
 
         def unset_tracing():
             debugfile.close()
-            sys.stderr.write("wrote pytestdebug information to %s\n" %
-                             debugfile.name)
+            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:
         p = py.path.local(pytest.__file__)
-        sys.stderr.write("This is pytest version %s, imported from %s\n" %
-                         (pytest.__version__, p))
+        sys.stderr.write(
+            "This is pytest version %s, imported from %s\n" % (pytest.__version__, p)
+        )
         plugininfo = getpluginversioninfo(config)
         if plugininfo:
             for line in plugininfo:
                 sys.stderr.write(line + "\n")
         return 0
     elif config.option.help:
         config._do_configure()
         showhelp(config)
         config._ensure_unconfigure()
         return 0
 
 
 def showhelp(config):
-    reporter = config.pluginmanager.get_plugin('terminalreporter')
+    reporter = config.pluginmanager.get_plugin("terminalreporter")
     tw = reporter._tw
     tw.write(config._parser.optparser.format_help())
     tw.line()
     tw.line()
-    tw.line("[pytest] ini-options in the first "
-            "pytest.ini|tox.ini|setup.cfg file found:")
+    tw.line(
+        "[pytest] ini-options in the first " "pytest.ini|tox.ini|setup.cfg file found:"
+    )
     tw.line()
 
     for name in config._parser._ininames:
         help, type, default = config._parser._inidict[name]
         if type is None:
             type = "string"
         spec = "%s (%s)" % (name, type)
         line = "  %-24s %s" % (spec, help)
         tw.line(line[:tw.fullwidth])
 
     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")
+        ("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)")
+    tw.line(
+        "(shown according to specified file_or_dir or current dir "
+        "if not specified; fixtures with leading '_' are only shown "
+        "with the '-v' option"
+    )
 
-    for warningreport in reporter.stats.get('warnings', []):
+    for warningreport in reporter.stats.get("warnings", []):
         tw.line("warning : " + warningreport.message, red=True)
     return
 
 
-conftest_options = [
-    ('pytest_plugins', 'list of plugin names to load'),
-]
+conftest_options = [("pytest_plugins", "list of plugin names to load")]
 
 
 def getpluginversioninfo(config):
     lines = []
     plugininfo = config.pluginmanager.list_plugin_distinfo()
     if plugininfo:
         lines.append("setuptools registered plugins:")
         for plugin, dist in plugininfo:
-            loc = getattr(plugin, '__file__', repr(plugin))
+            loc = getattr(plugin, "__file__", repr(plugin))
             content = "%s-%s at %s" % (dist.project_name, dist.version, loc)
             lines.append("  " + content)
     return lines
 
 
 def pytest_report_header(config):
     lines = []
     if config.option.debug or config.option.traceconfig:
-        lines.append("using: pytest-%s pylib-%s" %
-                     (pytest.__version__, py.__version__))
+        lines.append("using: pytest-%s pylib-%s" % (pytest.__version__, py.__version__))
 
         verinfo = getpluginversioninfo(config)
         if verinfo:
             lines.extend(verinfo)
 
     if config.option.traceconfig:
         lines.append("active plugins:")
         items = config.pluginmanager.list_name_plugin()
         for name, plugin in items:
-            if hasattr(plugin, '__file__'):
+            if hasattr(plugin, "__file__"):
                 r = plugin.__file__
             else:
                 r = repr(plugin)
             lines.append("    %-20s: %s" % (name, r))
     return lines
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/hookspec.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/hookspec.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/hookspec.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/hookspec.py
@@ -7,151 +7,226 @@ hookspec = HookspecMarker("pytest")
 # -------------------------------------------------------------------------
 # Initialization hooks called for every plugin
 # -------------------------------------------------------------------------
 
 
 @hookspec(historic=True)
 def pytest_addhooks(pluginmanager):
     """called at plugin registration time to allow adding new hooks via a call to
-    pluginmanager.add_hookspecs(module_or_class, prefix)."""
+    ``pluginmanager.add_hookspecs(module_or_class, prefix)``.
+
+
+    :param _pytest.config.PytestPluginManager pluginmanager: pytest plugin manager
+
+    .. note::
+        This hook is incompatible with ``hookwrapper=True``.
+    """
 
 
 @hookspec(historic=True)
 def pytest_namespace():
     """
-    DEPRECATED: this hook causes direct monkeypatching on pytest, its use is strongly discouraged
+    (**Deprecated**) this hook causes direct monkeypatching on pytest, its use is strongly discouraged
     return dict of name->object to be made globally available in
-    the pytest namespace.  This hook is called at plugin registration
-    time.
+    the pytest namespace.
+
+    This hook is called at plugin registration time.
+
+    .. note::
+        This hook is incompatible with ``hookwrapper=True``.
     """
 
 
 @hookspec(historic=True)
 def pytest_plugin_registered(plugin, manager):
-    """ a new pytest plugin got registered. """
+    """ a new pytest plugin got registered.
+
+    :param plugin: the plugin module or instance
+    :param _pytest.config.PytestPluginManager manager: pytest plugin manager
+
+    .. note::
+        This hook is incompatible with ``hookwrapper=True``.
+    """
 
 
 @hookspec(historic=True)
 def pytest_addoption(parser):
     """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
+    :arg _pytest.config.Parser 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(...)
         <_pytest.config.Parser.addini>`.
 
     Options can later be accessed through the
     :py:class:`config <_pytest.config.Config>` object, respectively:
 
     - :py:func:`config.getoption(name) <_pytest.config.Config.getoption>` to
       retrieve the value of a command line option.
 
     - :py:func:`config.getini(name) <_pytest.config.Config.getini>` to retrieve
       a value read from an ini-style file.
 
     The config object is passed around on many internal objects via the ``.config``
-    attribute or can be retrieved as the ``pytestconfig`` fixture or accessed
-    via (deprecated) ``pytest.config``.
+    attribute or can be retrieved as the ``pytestconfig`` fixture.
+
+    .. note::
+        This hook is incompatible with ``hookwrapper=True``.
     """
 
 
 @hookspec(historic=True)
 def pytest_configure(config):
     """
     Allows plugins and conftest files to perform initial configuration.
 
     This hook is called for every plugin and initial conftest file
     after command line options have been parsed.
 
     After that, the hook is called for other conftest files as they are
     imported.
 
-    :arg config: pytest config object
-    :type config: _pytest.config.Config
+    .. note::
+        This hook is incompatible with ``hookwrapper=True``.
+
+    :arg _pytest.config.Config config: pytest config object
     """
 
+
 # -------------------------------------------------------------------------
 # Bootstrapping hooks called for plugins registered early enough:
-# internal and 3rd party plugins as well as directly
-# discoverable conftest.py local plugins.
+# internal and 3rd party plugins.
 # -------------------------------------------------------------------------
 
 
 @hookspec(firstresult=True)
 def pytest_cmdline_parse(pluginmanager, args):
     """return initialized config object, parsing the specified args.
 
-    Stops at first non-None result, see :ref:`firstresult` """
+    Stops at first non-None result, see :ref:`firstresult`
+
+    .. note::
+        This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
+
+    :param _pytest.config.PytestPluginManager pluginmanager: pytest plugin manager
+    :param list[str] args: list of arguments passed on the command line
+    """
 
 
 def pytest_cmdline_preparse(config, args):
-    """(deprecated) modify command line arguments before option parsing. """
+    """(**Deprecated**) modify command line arguments before option parsing.
+
+    This hook is considered deprecated and will be removed in a future pytest version. Consider
+    using :func:`pytest_load_initial_conftests` instead.
+
+    .. note::
+        This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
+
+    :param _pytest.config.Config config: pytest config object
+    :param list[str] args: list of arguments passed on the command line
+    """
 
 
 @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.
 
-    Stops at first non-None result, see :ref:`firstresult` """
+    .. note::
+        This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
+
+    Stops at first non-None result, see :ref:`firstresult`
+
+    :param _pytest.config.Config config: pytest config object
+    """
 
 
 def pytest_load_initial_conftests(early_config, parser, args):
     """ implements the loading of initial conftest files ahead
-    of command line option parsing. """
+    of command line option parsing.
+
+    .. note::
+        This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
+
+    :param _pytest.config.Config early_config: pytest config object
+    :param list[str] args: list of arguments passed on the command line
+    :param _pytest.config.Parser parser: to add command line options
+    """
 
 
 # -------------------------------------------------------------------------
 # collection hooks
 # -------------------------------------------------------------------------
 
+
 @hookspec(firstresult=True)
 def pytest_collection(session):
-    """ perform the collection protocol for the given session.
+    """Perform the collection protocol for the given session.
 
-    Stops at first non-None result, see :ref:`firstresult` """
+    Stops at first non-None result, see :ref:`firstresult`.
+
+    :param _pytest.main.Session session: the pytest session object
+    """
 
 
 def pytest_collection_modifyitems(session, config, items):
     """ called after collection has been performed, may filter or re-order
-    the items in-place."""
+    the items in-place.
+
+    :param _pytest.main.Session session: the pytest session object
+    :param _pytest.config.Config config: pytest config object
+    :param List[_pytest.nodes.Item] items: list of item objects
+    """
 
 
 def pytest_collection_finish(session):
-    """ called after collection has been performed and modified. """
+    """ called after collection has been performed and modified.
+
+    :param _pytest.main.Session session: the pytest session object
+    """
 
 
 @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.
 
     Stops at first non-None result, see :ref:`firstresult`
+
+    :param str path: the path to analyze
+    :param _pytest.config.Config config: pytest config object
     """
 
 
 @hookspec(firstresult=True)
 def pytest_collect_directory(path, parent):
     """ called before traversing a directory for collection files.
 
-    Stops at first non-None result, see :ref:`firstresult` """
+    Stops at first non-None result, see :ref:`firstresult`
+
+    :param str path: the path to analyze
+    """
 
 
 def pytest_collect_file(path, parent):
     """ return collection Node or None for the given path. Any new node
-    needs to have the specified ``parent`` as a parent."""
+    needs to have the specified ``parent`` as a parent.
+
+    :param str path: the path to collect
+    """
+
 
 # logging hooks for collection
 
 
 def pytest_collectstart(collector):
     """ collector starts collecting. """
 
 
@@ -168,16 +243,17 @@ def pytest_deselected(items):
 
 
 @hookspec(firstresult=True)
 def pytest_make_collect_report(collector):
     """ perform ``collector.collect()`` and return a CollectReport.
 
     Stops at first non-None result, see :ref:`firstresult` """
 
+
 # -------------------------------------------------------------------------
 # Python test function related hooks
 # -------------------------------------------------------------------------
 
 
 @hookspec(firstresult=True)
 def pytest_pycollect_makemodule(path, parent):
     """ return a Module collector or None for the given path.
@@ -207,33 +283,42 @@ def pytest_generate_tests(metafunc):
 
 
 @hookspec(firstresult=True)
 def pytest_make_parametrize_id(config, val, argname):
     """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``.
     The parameter name is available as ``argname``, if required.
 
-    Stops at first non-None result, see :ref:`firstresult` """
+    Stops at first non-None result, see :ref:`firstresult`
+
+    :param _pytest.config.Config config: pytest config object
+    :param val: the parametrized value
+    :param str argname: the automatic parameter name produced by pytest
+    """
+
 
 # -------------------------------------------------------------------------
 # generic runtest related hooks
 # -------------------------------------------------------------------------
 
 
 @hookspec(firstresult=True)
 def pytest_runtestloop(session):
     """ called for performing the main runtest loop
     (after collection finished).
 
-    Stops at first non-None result, see :ref:`firstresult` """
+    Stops at first non-None result, see :ref:`firstresult`
+
+    :param _pytest.main.Session session: the pytest session object
+    """
 
 
 def pytest_itemstart(item, node):
-    """ (deprecated, use pytest_runtest_logstart). """
+    """(**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
     reporting hooks.
 
@@ -245,17 +330,35 @@ def pytest_runtest_protocol(item, nextit
 
     :return boolean: True if no further hook implementations should be invoked.
 
 
     Stops at first non-None result, see :ref:`firstresult` """
 
 
 def pytest_runtest_logstart(nodeid, location):
-    """ signal the start of running a single test item. """
+    """ signal the start of running a single test item.
+
+    This hook will be called **before** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and
+    :func:`pytest_runtest_teardown` hooks.
+
+    :param str nodeid: full id of the item
+    :param location: a triple of ``(filename, linenum, testname)``
+    """
+
+
+def pytest_runtest_logfinish(nodeid, location):
+    """ signal the complete finish of running a single test item.
+
+    This hook will be called **after** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and
+    :func:`pytest_runtest_teardown` hooks.
+
+    :param str nodeid: full id of the item
+    :param location: a triple of ``(filename, linenum, testname)``
+    """
 
 
 def pytest_runtest_setup(item):
     """ called before ``pytest_runtest_call(item)``. """
 
 
 def pytest_runtest_call(item):
     """ called to execute the test ``item``. """
@@ -279,72 +382,97 @@ def pytest_runtest_makereport(item, call
 
     Stops at first non-None result, see :ref:`firstresult` """
 
 
 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.
 
-    Stops at first non-None result, see :ref:`firstresult` """
+    :return: The return value of the call to the fixture function
+
+    Stops at first non-None result, see :ref:`firstresult`
+
+    .. note::
+        If the fixture function returns None, other implementations of
+        this hook function will continue to be called, according to the
+        behavior of the :ref:`firstresult` option.
+    """
 
 
 def pytest_fixture_post_finalizer(fixturedef, request):
     """ 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
 # -------------------------------------------------------------------------
 
 
 def pytest_sessionstart(session):
-    """ before session.main() is called. """
+    """ called after the ``Session`` object has been created and before performing collection
+    and entering the run test loop.
+
+    :param _pytest.main.Session session: the pytest session object
+    """
 
 
 def pytest_sessionfinish(session, exitstatus):
-    """ whole test run finishes. """
+    """ called after whole test run finished, right before returning the exit status to the system.
+
+    :param _pytest.main.Session session: the pytest session object
+    :param int exitstatus: the status which pytest will return to the system
+    """
 
 
 def pytest_unconfigure(config):
-    """ called before test process is exited.  """
+    """ called before test process is exited.
+
+    :param _pytest.config.Config config: pytest config object
+    """
 
 
 # -------------------------------------------------------------------------
 # hooks for customizing the assert methods
 # -------------------------------------------------------------------------
 
+
 def pytest_assertrepr_compare(config, op, left, right):
     """return explanation for comparisons in failing assert expressions.
 
     Return None for no custom explanation, otherwise return a list
     of strings.  The strings will be joined by newlines but any newlines
     *in* a string will be escaped.  Note that all but the first line will
     be indented slightly, the intention is for the first line to be a summary.
+
+    :param _pytest.config.Config config: pytest config object
     """
 
+
 # -------------------------------------------------------------------------
 # hooks for influencing reporting (invoked from _pytest_terminal)
 # -------------------------------------------------------------------------
 
 
 def pytest_report_header(config, startdir):
     """ return a string or list of strings to be displayed as header info for terminal reporting.
 
-    :param config: the pytest config object.
+    :param _pytest.config.Config config: pytest config object
     :param startdir: py.path object with the starting dir
 
     .. 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>`.
     """
@@ -353,50 +481,63 @@ def pytest_report_header(config, startdi
 def pytest_report_collectionfinish(config, startdir, items):
     """
     .. versionadded:: 3.2
 
     return a string or list of strings to be displayed after collection has finished successfully.
 
     This strings will be displayed after the standard "collected X items" message.
 
-    :param config: the pytest config object.
+    :param _pytest.config.Config config: pytest config object
     :param startdir: py.path object with the starting dir
     :param items: list of pytest items that are going to be executed; this list should not be modified.
     """
 
 
 @hookspec(firstresult=True)
 def pytest_report_teststatus(report):
     """ return result-category, shortletter and verbose word for reporting.
 
     Stops at first non-None result, see :ref:`firstresult` """
 
 
 def pytest_terminal_summary(terminalreporter, exitstatus):
-    """ add additional section in terminal summary reporting.  """
+    """Add a section to terminal summary reporting.
+
+    :param _pytest.terminal.TerminalReporter terminalreporter: the internal terminal reporter object
+    :param int exitstatus: the exit status that will be reported back to the OS
+
+    .. versionadded:: 3.5
+        The ``config`` parameter.
+    """
 
 
 @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
-    if the warning is not tied to a partilar node/location)."""
+    if the warning is not tied to a particular node/location).
+
+    .. note::
+        This hook is incompatible with ``hookwrapper=True``.
+    """
+
 
 # -------------------------------------------------------------------------
 # doctest hooks
 # -------------------------------------------------------------------------
 
 
 @hookspec(firstresult=True)
 def pytest_doctest_prepare_content(content):
     """ return processed content for a given doctest
 
     Stops at first non-None result, see :ref:`firstresult` """
 
+
 # -------------------------------------------------------------------------
 # error handling and internal debugging hooks
 # -------------------------------------------------------------------------
 
 
 def pytest_internalerror(excrepr, excinfo):
     """ called for internal errors. """
 
@@ -413,11 +554,10 @@ def pytest_exception_interact(node, call
     that is not an internal exception like ``skip.Exception``.
     """
 
 
 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
+    :param _pytest.config.Config config: pytest config object
     """
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/junitxml.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/junitxml.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/junitxml.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/junitxml.py
@@ -34,44 +34,45 @@ class Junit(py.xml.Namespace):
 
 
 # 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
 # chars is: Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
 #                    | [#x10000-#x10FFFF]
 _legal_chars = (0x09, 0x0A, 0x0d)
-_legal_ranges = (
-    (0x20, 0x7E), (0x80, 0xD7FF), (0xE000, 0xFFFD), (0x10000, 0x10FFFF),
-)
+_legal_ranges = ((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
+    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())
         if i <= 0xFF:
-            return unicode('#x%02X') % i
+            return unicode("#x%02X") % i
         else:
-            return unicode('#x%04X') % i
+            return unicode("#x%04X") % i
 
     return py.xml.raw(illegal_xml_re.sub(repl, py.xml.escape(arg)))
 
 
 class _NodeReporter(object):
+
     def __init__(self, nodeid, xml):
 
         self.id = nodeid
         self.xml = xml
         self.add_stats = self.xml.add_stats
         self.duration = 0
         self.properties = []
         self.nodes = []
@@ -80,222 +81,315 @@ class _NodeReporter(object):
 
     def append(self, node):
         self.xml.add_stats(type(node).__name__)
         self.nodes.append(node)
 
     def add_property(self, name, value):
         self.properties.append((str(name), bin_xml_escape(value)))
 
+    def add_attribute(self, name, value):
+        self.attrs[str(name)] = bin_xml_escape(value)
+
     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 ''
+            return Junit.properties(
+                [
+                    Junit.property(name=name, value=value)
+                    for name, value in self.properties
+                ]
+            )
+        return ""
 
     def record_testreport(self, testreport):
         assert not self.testcase
         names = mangle_test_address(testreport.nodeid)
+        existing_attrs = self.attrs
         classnames = names[:-1]
         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]
         if hasattr(testreport, "url"):
             attrs["url"] = testreport.url
         self.attrs = attrs
+        self.attrs.update(existing_attrs)  # restore any user-defined attributes
 
     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'):
-            content = getattr(report, 'capstd' + capname)
+        content_out = report.capstdout
+        content_log = report.caplog
+        content_err = report.capstderr
+
+        if content_log or content_out:
+            if content_log and self.xml.logging == "system-out":
+                if content_out:
+                    # syncing stdout and the log-output is not done yet. It's
+                    # probably not worth the effort. Therefore, first the captured
+                    # stdout is shown and then the captured logs.
+                    content = "\n".join(
+                        [
+                            " Captured Stdout ".center(80, "-"),
+                            content_out,
+                            "",
+                            " Captured Log ".center(80, "-"),
+                            content_log,
+                        ]
+                    )
+                else:
+                    content = content_log
+            else:
+                content = content_out
+
             if content:
-                tag = getattr(Junit, 'system-' + capname)
+                tag = getattr(Junit, "system-out")
+                self.append(tag(bin_xml_escape(content)))
+
+        if content_log or content_err:
+            if content_log and self.xml.logging == "system-err":
+                if content_err:
+                    content = "\n".join(
+                        [
+                            " Captured Stderr ".center(80, "-"),
+                            content_err,
+                            "",
+                            " Captured Log ".center(80, "-"),
+                            content_log,
+                        ]
+                    )
+                else:
+                    content = content_log
+            else:
+                content = content_err
+
+            if content:
+                tag = getattr(Junit, "system-err")
                 self.append(tag(bin_xml_escape(content)))
 
     def append_pass(self, report):
-        self.add_stats('passed')
+        self.add_stats("passed")
 
     def append_failure(self, report):
         # msg = str(report.longrepr.reprtraceback.extraline)
         if hasattr(report, "wasxfail"):
-            self._add_simple(
-                Junit.skipped,
-                "xfail-marked test passes unexpectedly")
+            self._add_simple(Junit.skipped, "xfail-marked test passes unexpectedly")
         else:
             if hasattr(report.longrepr, "reprcrash"):
                 message = report.longrepr.reprcrash.message
             elif isinstance(report.longrepr, (unicode, str)):
                 message = report.longrepr
             else:
                 message = str(report.longrepr)
             message = bin_xml_escape(message)
             fail = Junit.failure(message=message)
             fail.append(bin_xml_escape(report.longrepr))
             self.append(fail)
 
     def append_collect_error(self, report):
         # msg = str(report.longrepr.reprtraceback.extraline)
-        self.append(Junit.error(bin_xml_escape(report.longrepr),
-                                message="collection failure"))
+        self.append(
+            Junit.error(bin_xml_escape(report.longrepr), message="collection failure")
+        )
 
     def append_collect_skipped(self, report):
-        self._add_simple(
-            Junit.skipped, "collection skipped", report.longrepr)
+        self._add_simple(Junit.skipped, "collection skipped", report.longrepr)
 
     def append_error(self, report):
-        if getattr(report, 'when', None) == 'teardown':
+        if getattr(report, "when", None) == "teardown":
             msg = "test teardown failure"
         else:
             msg = "test setup failure"
-        self._add_simple(
-            Junit.error, msg, report.longrepr)
+        self._add_simple(Junit.error, msg, report.longrepr)
 
     def append_skipped(self, report):
         if hasattr(report, "wasxfail"):
-            self._add_simple(
-                Junit.skipped, "expected test failure", report.wasxfail
-            )
+            self._add_simple(Junit.skipped, "expected test failure", report.wasxfail)
         else:
             filename, lineno, skipreason = report.longrepr
             if skipreason.startswith("Skipped: "):
                 skipreason = bin_xml_escape(skipreason[9:])
             self.append(
-                Junit.skipped("%s:%s: %s" % (filename, lineno, skipreason),
-                              type="pytest.skip",
-                              message=skipreason))
-        self.write_captured_output(report)
+                Junit.skipped(
+                    "%s:%s: %s" % (filename, lineno, skipreason),
+                    type="pytest.skip",
+                    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.
+def record_property(request):
+    """Add an extra properties the calling test.
+    User properties become part of the test report and are available to the
+    configured reporters, like JUnit XML.
     The fixture is callable with ``(name, value)``, with value being automatically
     xml-encoded.
+
+    Example::
+
+        def test_function(record_property):
+            record_property("example_key", 1)
+    """
+
+    def append_property(name, value):
+        request.node.user_properties.append((name, value))
+
+    return append_property
+
+
+@pytest.fixture
+def record_xml_property(record_property):
+    """(Deprecated) use record_property."""
+    import warnings
+    from _pytest import deprecated
+
+    warnings.warn(deprecated.RECORD_XML_PROPERTY, DeprecationWarning, stacklevel=2)
+
+    return record_property
+
+
+@pytest.fixture
+def record_xml_attribute(request):
+    """Add extra xml attributes 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',
+        code="C3", message="record_xml_attribute 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
+        return node_reporter.add_attribute
     else:
-        def add_property_noop(name, value):
+
+        def add_attr_noop(name, value):
             pass
 
-        return add_property_noop
+        return add_attr_noop
 
 
 def pytest_addoption(parser):
     group = parser.getgroup("terminal reporting")
     group.addoption(
-        '--junitxml', '--junit-xml',
+        "--junitxml",
+        "--junit-xml",
         action="store",
         dest="xmlpath",
         metavar="path",
         type=functools.partial(filename_arg, optname="--junitxml"),
         default=None,
-        help="create junit-xml style report file at given path.")
+        help="create junit-xml style report file at given path.",
+    )
     group.addoption(
-        '--junitprefix', '--junit-prefix',
+        "--junitprefix",
+        "--junit-prefix",
         action="store",
         metavar="str",
         default=None,
-        help="prepend prefix to classnames in junit-xml output")
-    parser.addini("junit_suite_name", "Test suite name for JUnit report", default="pytest")
+        help="prepend prefix to classnames in junit-xml output",
+    )
+    parser.addini(
+        "junit_suite_name", "Test suite name for JUnit report", default="pytest"
+    )
+    parser.addini(
+        "junit_logging",
+        "Write captured log messages to JUnit report: "
+        "one of no|system-out|system-err",
+        default="no",
+    )  # choices=['no', 'stdout', 'stderr'])
 
 
 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.getini("junit_suite_name"))
+    if xmlpath and not hasattr(config, "slaveinput"):
+        config._xml = LogXML(
+            xmlpath,
+            config.option.junitprefix,
+            config.getini("junit_suite_name"),
+            config.getini("junit_logging"),
+        )
         config.pluginmanager.register(config._xml)
 
 
 def pytest_unconfigure(config):
-    xml = getattr(config, '_xml', None)
+    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('[')
+    path, possible_open_bracket, params = address.partition("[")
     names = path.split("::")
     try:
-        names.remove('()')
+        names.remove("()")
     except ValueError:
         pass
     # convert file path to dotted path
-    names[0] = names[0].replace(nodes.SEP, '.')
+    names[0] = names[0].replace(nodes.SEP, ".")
     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, suite_name="pytest"):
+
+    def __init__(self, logfile, prefix, suite_name="pytest", logging="no"):
         logfile = os.path.expanduser(os.path.expandvars(logfile))
         self.logfile = os.path.normpath(os.path.abspath(logfile))
         self.prefix = prefix
         self.suite_name = suite_name
-        self.stats = dict.fromkeys([
-            'error',
-            'passed',
-            'failure',
-            'skipped',
-        ], 0)
+        self.logging = logging
+        self.stats = dict.fromkeys(["error", "passed", "failure", "skipped"], 0)
         self.node_reporters = {}  # nodeid -> _NodeReporter
         self.node_reporters_ordered = []
         self.global_properties = []
         # List of reports that failed on call but teardown is pending.
         self.open_reports = []
         self.cnt_double_fail_tests = 0
 
     def finalize(self, report):
-        nodeid = getattr(report, 'nodeid', report)
+        nodeid = getattr(report, "nodeid", report)
         # local hack to handle xdist report order
-        slavenode = getattr(report, 'node', None)
+        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)
+        nodeid = getattr(report, "nodeid", report)
         # local hack to handle xdist report order
-        slavenode = getattr(report, 'node', None)
+        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)
@@ -343,22 +437,27 @@ class LogXML(object):
                 reporter = self._opentestcase(report)
                 reporter.append_pass(report)
         elif report.failed:
             if report.when == "teardown":
                 # The following vars are needed when xdist plugin is used
                 report_wid = getattr(report, "worker_id", None)
                 report_ii = getattr(report, "item_index", None)
                 close_report = next(
-                    (rep for rep in self.open_reports
-                     if (rep.nodeid == report.nodeid and
-                         getattr(rep, "item_index", None) == report_ii and
-                         getattr(rep, "worker_id", None) == report_wid
-                         )
-                     ), None)
+                    (
+                        rep
+                        for rep in self.open_reports
+                        if (
+                            rep.nodeid == report.nodeid
+                            and getattr(rep, "item_index", None) == report_ii
+                            and getattr(rep, "worker_id", None) == report_wid
+                        )
+                    ),
+                    None,
+                )
                 if close_report:
                     # We need to open new testcase in case we have failure in
                     # call and error in teardown in order to follow junit
                     # schema
                     self.finalize(close_report)
                     self.cnt_double_fail_tests += 1
             reporter = self._opentestcase(report)
             if report.when == "call":
@@ -368,86 +467,103 @@ class LogXML(object):
                 reporter.append_error(report)
         elif report.skipped:
             reporter = self._opentestcase(report)
             reporter.append_skipped(report)
         self.update_testcase_duration(report)
         if report.when == "teardown":
             reporter = self._opentestcase(report)
             reporter.write_captured_output(report)
+
+            for propname, propvalue in report.user_properties:
+                reporter.add_property(propname, propvalue)
+
             self.finalize(report)
             report_wid = getattr(report, "worker_id", None)
             report_ii = getattr(report, "item_index", None)
             close_report = next(
-                (rep for rep in self.open_reports
-                 if (rep.nodeid == report.nodeid and
-                     getattr(rep, "item_index", None) == report_ii and
-                     getattr(rep, "worker_id", None) == report_wid
-                     )
-                 ), None)
+                (
+                    rep
+                    for rep in self.open_reports
+                    if (
+                        rep.nodeid == report.nodeid
+                        and getattr(rep, "item_index", None) == report_ii
+                        and getattr(rep, "worker_id", None) == report_wid
+                    )
+                ),
+                None,
+            )
             if close_report:
                 self.open_reports.remove(close_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)
+        reporter.duration += getattr(report, "duration", 0.0)
 
     def pytest_collectreport(self, report):
         if not report.passed:
             reporter = self._opentestcase(report)
             if report.failed:
                 reporter.append_collect_error(report)
             else:
                 reporter.append_collect_skipped(report)
 
     def pytest_internalerror(self, excrepr):
-        reporter = self.node_reporter('internal')
-        reporter.attrs.update(classname="pytest", name='internal')
-        reporter._add_simple(Junit.error, 'internal error', excrepr)
+        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()
 
     def pytest_sessionfinish(self):
         dirname = os.path.dirname(os.path.abspath(self.logfile))
         if not os.path.isdir(dirname):
             os.makedirs(dirname)
-        logfile = open(self.logfile, 'w', encoding='utf-8')
+        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.stats['passed'] + self.stats['failure'] +
-                    self.stats['skipped'] + self.stats['error'] -
-                    self.cnt_double_fail_tests)
+        numtests = (
+            self.stats["passed"]
+            + self.stats["failure"]
+            + self.stats["skipped"]
+            + self.stats["error"]
+            - self.cnt_double_fail_tests
+        )
         logfile.write('<?xml version="1.0" encoding="utf-8"?>')
 
-        logfile.write(Junit.testsuite(
-            self._get_global_properties_node(),
-            [x.to_xml() for x in self.node_reporters_ordered],
-            name=self.suite_name,
-            errors=self.stats['error'],
-            failures=self.stats['failure'],
-            skips=self.stats['skipped'],
-            tests=numtests,
-            time="%.3f" % suite_time_delta, ).unicode(indent=0))
+        logfile.write(
+            Junit.testsuite(
+                self._get_global_properties_node(),
+                [x.to_xml() for x in self.node_reporters_ordered],
+                name=self.suite_name,
+                errors=self.stats["error"],
+                failures=self.stats["failure"],
+                skips=self.stats["skipped"],
+                tests=numtests,
+                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 ''
+        return ""
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/logging.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/logging.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/logging.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/logging.py
@@ -1,149 +1,259 @@
+""" Access and control log capturing. """
 from __future__ import absolute_import, division, print_function
 
 import logging
 from contextlib import closing, contextmanager
-import sys
+import re
 import six
 
+from _pytest.config import create_terminal_writer
 import pytest
 import py
 
 
-DEFAULT_LOG_FORMAT = '%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s'
-DEFAULT_LOG_DATE_FORMAT = '%H:%M:%S'
+DEFAULT_LOG_FORMAT = "%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s"
+DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S"
+
+
+class ColoredLevelFormatter(logging.Formatter):
+    """
+    Colorize the %(levelname)..s part of the log format passed to __init__.
+    """
+
+    LOGLEVEL_COLOROPTS = {
+        logging.CRITICAL: {"red"},
+        logging.ERROR: {"red", "bold"},
+        logging.WARNING: {"yellow"},
+        logging.WARN: {"yellow"},
+        logging.INFO: {"green"},
+        logging.DEBUG: {"purple"},
+        logging.NOTSET: set(),
+    }
+    LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-]?\d*s)")
+
+    def __init__(self, terminalwriter, *args, **kwargs):
+        super(ColoredLevelFormatter, self).__init__(*args, **kwargs)
+        if six.PY2:
+            self._original_fmt = self._fmt
+        else:
+            self._original_fmt = self._style._fmt
+        self._level_to_fmt_mapping = {}
+
+        levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt)
+        if not levelname_fmt_match:
+            return
+        levelname_fmt = levelname_fmt_match.group()
+
+        for level, color_opts in self.LOGLEVEL_COLOROPTS.items():
+            formatted_levelname = levelname_fmt % {
+                "levelname": logging.getLevelName(level)
+            }
+
+            # add ANSI escape sequences around the formatted levelname
+            color_kwargs = {name: True for name in color_opts}
+            colorized_formatted_levelname = terminalwriter.markup(
+                formatted_levelname, **color_kwargs
+            )
+            self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub(
+                colorized_formatted_levelname, self._fmt
+            )
+
+    def format(self, record):
+        fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt)
+        if six.PY2:
+            self._fmt = fmt
+        else:
+            self._style._fmt = fmt
+        return super(ColoredLevelFormatter, self).format(record)
 
 
 def get_option_ini(config, *names):
     for name in names:
         ret = config.getoption(name)  # 'default' arg won't work as expected
         if ret is None:
             ret = config.getini(name)
         if ret:
             return ret
 
 
 def pytest_addoption(parser):
     """Add options to control log capturing."""
-    group = parser.getgroup('logging')
+    group = parser.getgroup("logging")
 
     def add_option_ini(option, dest, default=None, type=None, **kwargs):
-        parser.addini(dest, default=default, type=type,
-                      help='default value for ' + option)
+        parser.addini(
+            dest, default=default, type=type, help="default value for " + option
+        )
         group.addoption(option, dest=dest, **kwargs)
 
     add_option_ini(
-        '--no-print-logs',
-        dest='log_print', action='store_const', const=False, default=True,
-        type='bool',
-        help='disable printing caught logs on failed tests.')
+        "--no-print-logs",
+        dest="log_print",
+        action="store_const",
+        const=False,
+        default=True,
+        type="bool",
+        help="disable printing caught logs on failed tests.",
+    )
     add_option_ini(
-        '--log-level',
-        dest='log_level', default=None,
-        help='logging level used by the logging module')
+        "--log-level",
+        dest="log_level",
+        default=None,
+        help="logging level used by the logging module",
+    )
     add_option_ini(
-        '--log-format',
-        dest='log_format', default=DEFAULT_LOG_FORMAT,
-        help='log format as used by the logging module.')
+        "--log-format",
+        dest="log_format",
+        default=DEFAULT_LOG_FORMAT,
+        help="log format as used by the logging module.",
+    )
     add_option_ini(
-        '--log-date-format',
-        dest='log_date_format', default=DEFAULT_LOG_DATE_FORMAT,
-        help='log date format as used by the logging module.')
+        "--log-date-format",
+        dest="log_date_format",
+        default=DEFAULT_LOG_DATE_FORMAT,
+        help="log date format as used by the logging module.",
+    )
+    parser.addini(
+        "log_cli",
+        default=False,
+        type="bool",
+        help='enable log display during test run (also known as "live logging").',
+    )
     add_option_ini(
-        '--log-cli-level',
-        dest='log_cli_level', default=None,
-        help='cli logging level.')
+        "--log-cli-level", dest="log_cli_level", default=None, help="cli logging level."
+    )
     add_option_ini(
-        '--log-cli-format',
-        dest='log_cli_format', default=None,
-        help='log format as used by the logging module.')
+        "--log-cli-format",
+        dest="log_cli_format",
+        default=None,
+        help="log format as used by the logging module.",
+    )
     add_option_ini(
-        '--log-cli-date-format',
-        dest='log_cli_date_format', default=None,
-        help='log date format as used by the logging module.')
+        "--log-cli-date-format",
+        dest="log_cli_date_format",
+        default=None,
+        help="log date format as used by the logging module.",
+    )
     add_option_ini(
-        '--log-file',
-        dest='log_file', default=None,
-        help='path to a file when logging will be written to.')
+        "--log-file",
+        dest="log_file",
+        default=None,
+        help="path to a file when logging will be written to.",
+    )
     add_option_ini(
-        '--log-file-level',
-        dest='log_file_level', default=None,
-        help='log file logging level.')
+        "--log-file-level",
+        dest="log_file_level",
+        default=None,
+        help="log file logging level.",
+    )
     add_option_ini(
-        '--log-file-format',
-        dest='log_file_format', default=DEFAULT_LOG_FORMAT,
-        help='log format as used by the logging module.')
+        "--log-file-format",
+        dest="log_file_format",
+        default=DEFAULT_LOG_FORMAT,
+        help="log format as used by the logging module.",
+    )
     add_option_ini(
-        '--log-file-date-format',
-        dest='log_file_date_format', default=DEFAULT_LOG_DATE_FORMAT,
-        help='log date format as used by the logging module.')
+        "--log-file-date-format",
+        dest="log_file_date_format",
+        default=DEFAULT_LOG_DATE_FORMAT,
+        help="log date format as used by the logging module.",
+    )
 
 
 @contextmanager
-def logging_using_handler(handler, logger=None):
-    """Context manager that safely registers a given handler."""
-    logger = logger or logging.getLogger(logger)
-
-    if handler in logger.handlers:  # reentrancy
-        # Adding the same handler twice would confuse logging system.
-        # Just don't do that.
-        yield
-    else:
-        logger.addHandler(handler)
-        try:
-            yield
-        finally:
-            logger.removeHandler(handler)
-
-
-@contextmanager
-def catching_logs(handler, formatter=None,
-                  level=logging.NOTSET, logger=None):
+def catching_logs(handler, formatter=None, level=None):
     """Context manager that prepares the whole logging machinery properly."""
-    logger = logger or logging.getLogger(logger)
+    root_logger = logging.getLogger()
 
     if formatter is not None:
         handler.setFormatter(formatter)
-    handler.setLevel(level)
+    if level is not None:
+        handler.setLevel(level)
+
+    # Adding the same handler twice would confuse logging system.
+    # Just don't do that.
+    add_new_handler = handler not in root_logger.handlers
 
-    with logging_using_handler(handler, logger):
-        orig_level = logger.level
-        logger.setLevel(min(orig_level, level))
-        try:
-            yield handler
-        finally:
-            logger.setLevel(orig_level)
+    if add_new_handler:
+        root_logger.addHandler(handler)
+    if level is not None:
+        orig_level = root_logger.level
+        root_logger.setLevel(min(orig_level, level))
+    try:
+        yield handler
+    finally:
+        if level is not None:
+            root_logger.setLevel(orig_level)
+        if add_new_handler:
+            root_logger.removeHandler(handler)
 
 
 class LogCaptureHandler(logging.StreamHandler):
     """A logging handler that stores log records and the log text."""
 
     def __init__(self):
         """Creates a new log handler."""
         logging.StreamHandler.__init__(self, py.io.TextIO())
         self.records = []
 
     def emit(self, record):
         """Keep the log records in a list in addition to the log text."""
         self.records.append(record)
         logging.StreamHandler.emit(self, record)
 
+    def reset(self):
+        self.records = []
+        self.stream = py.io.TextIO()
+
 
 class LogCaptureFixture(object):
     """Provides access and control of log capturing."""
 
     def __init__(self, item):
         """Creates a new funcarg."""
         self._item = item
+        self._initial_log_levels = {}  # type: Dict[str, int] # dict of log name -> log level
+
+    def _finalize(self):
+        """Finalizes the fixture.
+
+        This restores the log levels changed by :meth:`set_level`.
+        """
+        # restore log levels
+        for logger_name, level in self._initial_log_levels.items():
+            logger = logging.getLogger(logger_name)
+            logger.setLevel(level)
 
     @property
     def handler(self):
+        """
+        :rtype: LogCaptureHandler
+        """
         return self._item.catch_log_handler
 
+    def get_records(self, when):
+        """
+        Get the logging records for one of the possible test phases.
+
+        :param str when:
+            Which test phase to obtain the records from. Valid values are: "setup", "call" and "teardown".
+
+        :rtype: List[logging.LogRecord]
+        :return: the list of captured records at the given stage
+
+        .. versionadded:: 3.4
+        """
+        handler = self._item.catch_log_handlers.get(when)
+        if handler:
+            return handler.records
+        else:
+            return []
+
     @property
     def text(self):
         """Returns the log text."""
         return self.handler.stream.getvalue()
 
     @property
     def records(self):
         """Returns the list of log records."""
@@ -156,64 +266,67 @@ class LogCaptureFixture(object):
 
         The format of the tuple is:
 
             (logger_name, log_level, message)
         """
         return [(r.name, r.levelno, r.getMessage()) for r in self.records]
 
     def clear(self):
-        """Reset the list of log records."""
-        self.handler.records = []
+        """Reset the list of log records and the captured log text."""
+        self.handler.reset()
 
     def set_level(self, level, logger=None):
-        """Sets the level for capturing of logs.
+        """Sets the level for capturing of logs. The level will be restored to its previous value at the end of
+        the test.
+
+        :param int level: the logger to level.
+        :param str logger: the logger to update the level. If not given, the root logger level is updated.
 
-        By default, the level is set on the handler used to capture
-        logs. Specify a logger name to instead set the level of any
-        logger.
+        .. versionchanged:: 3.4
+            The levels of the loggers changed by this function will be restored to their initial values at the
+            end of the test.
         """
-        if logger is None:
-            logger = self.handler
-        else:
-            logger = logging.getLogger(logger)
+        logger_name = logger
+        logger = logging.getLogger(logger_name)
+        # save the original log-level to restore it during teardown
+        self._initial_log_levels.setdefault(logger_name, logger.level)
         logger.setLevel(level)
 
     @contextmanager
     def at_level(self, level, logger=None):
-        """Context manager that sets the level for capturing of logs.
+        """Context manager that sets the level for capturing of logs. After the end of the 'with' statement the
+        level is restored to its original value.
 
-        By default, the level is set on the handler used to capture
-        logs. Specify a logger name to instead set the level of any
-        logger.
+        :param int level: the logger to level.
+        :param str logger: the logger to update the level. If not given, the root logger level is updated.
         """
-        if logger is None:
-            logger = self.handler
-        else:
-            logger = logging.getLogger(logger)
-
+        logger = logging.getLogger(logger)
         orig_level = logger.level
         logger.setLevel(level)
         try:
             yield
         finally:
             logger.setLevel(orig_level)
 
 
 @pytest.fixture
 def caplog(request):
     """Access and control log capturing.
 
     Captured logs are available through the following methods::
 
-    * caplog.text()          -> string containing formatted log output
-    * caplog.records()       -> list of logging.LogRecord instances
-    * caplog.record_tuples() -> list of (logger_name, level, message) tuples
+    * caplog.text            -> string containing formatted log output
+    * caplog.records         -> list of logging.LogRecord instances
+    * caplog.record_tuples   -> list of (logger_name, level, message) tuples
+    * caplog.clear()         -> clear captured records and formatted log output string
     """
-    return LogCaptureFixture(request.node)
+    result = LogCaptureFixture(request.node)
+    yield result
+    result._finalize()
 
 
 def get_actual_log_level(config, *setting_names):
     """Return the actual logging level."""
 
     for setting_name in setting_names:
         log_level = config.getoption(setting_name)
         if log_level is None:
@@ -225,113 +338,238 @@ def get_actual_log_level(config, *settin
 
     if isinstance(log_level, six.string_types):
         log_level = log_level.upper()
     try:
         return int(getattr(logging, log_level, log_level))
     except ValueError:
         # Python logging does not recognise this as a logging level
         raise pytest.UsageError(
-            "'{0}' is not recognized as a logging level name for "
-            "'{1}'. Please consider passing the "
-            "logging level num instead.".format(
-                log_level,
-                setting_name))
+            "'{}' is not recognized as a logging level name for "
+            "'{}'. Please consider passing the "
+            "logging level num instead.".format(log_level, setting_name)
+        )
 
 
 def pytest_configure(config):
-    config.pluginmanager.register(LoggingPlugin(config),
-                                  'logging-plugin')
+    config.pluginmanager.register(LoggingPlugin(config), "logging-plugin")
+
+
+@contextmanager
+def _dummy_context_manager():
+    yield
 
 
 class LoggingPlugin(object):
     """Attaches to the logging module and captures log messages for each test.
     """
 
     def __init__(self, config):
         """Creates a new plugin to capture log messages.
 
         The formatter can be safely shared across all handlers so
         create a single one for the entire test session here.
         """
-        self.log_cli_level = get_actual_log_level(
-            config, 'log_cli_level', 'log_level') or logging.WARNING
+        self._config = config
 
-        self.print_logs = get_option_ini(config, 'log_print')
-        self.formatter = logging.Formatter(
-            get_option_ini(config, 'log_format'),
-            get_option_ini(config, 'log_date_format'))
+        # enable verbose output automatically if live logging is enabled
+        if self._log_cli_enabled() and not config.getoption("verbose"):
+            # sanity check: terminal reporter should not have been loaded at this point
+            assert self._config.pluginmanager.get_plugin("terminalreporter") is None
+            config.option.verbose = 1
 
-        log_cli_handler = logging.StreamHandler(sys.stderr)
-        log_cli_format = get_option_ini(
-            config, 'log_cli_format', 'log_format')
-        log_cli_date_format = get_option_ini(
-            config, 'log_cli_date_format', 'log_date_format')
-        log_cli_formatter = logging.Formatter(
-            log_cli_format,
-            datefmt=log_cli_date_format)
-        self.log_cli_handler = log_cli_handler  # needed for a single unittest
-        self.live_logs = catching_logs(log_cli_handler,
-                                       formatter=log_cli_formatter,
-                                       level=self.log_cli_level)
+        self.print_logs = get_option_ini(config, "log_print")
+        self.formatter = logging.Formatter(
+            get_option_ini(config, "log_format"),
+            get_option_ini(config, "log_date_format"),
+        )
+        self.log_level = get_actual_log_level(config, "log_level")
 
-        log_file = get_option_ini(config, 'log_file')
+        log_file = get_option_ini(config, "log_file")
         if log_file:
-            self.log_file_level = get_actual_log_level(
-                config, 'log_file_level') or logging.WARNING
+            self.log_file_level = get_actual_log_level(config, "log_file_level")
 
-            log_file_format = get_option_ini(
-                config, 'log_file_format', 'log_format')
+            log_file_format = get_option_ini(config, "log_file_format", "log_format")
             log_file_date_format = get_option_ini(
-                config, 'log_file_date_format', 'log_date_format')
-            self.log_file_handler = logging.FileHandler(
-                log_file,
-                # Each pytest runtests session will write to a clean logfile
-                mode='w')
+                config, "log_file_date_format", "log_date_format"
+            )
+            # Each pytest runtests session will write to a clean logfile
+            self.log_file_handler = logging.FileHandler(log_file, mode="w")
             log_file_formatter = logging.Formatter(
-                log_file_format,
-                datefmt=log_file_date_format)
+                log_file_format, datefmt=log_file_date_format
+            )
             self.log_file_handler.setFormatter(log_file_formatter)
         else:
             self.log_file_handler = None
 
+        # initialized during pytest_runtestloop
+        self.log_cli_handler = None
+
+    def _log_cli_enabled(self):
+        """Return True if log_cli should be considered enabled, either explicitly
+        or because --log-cli-level was given in the command-line.
+        """
+        return self._config.getoption(
+            "--log-cli-level"
+        ) is not None or self._config.getini(
+            "log_cli"
+        )
+
     @contextmanager
     def _runtest_for(self, item, when):
         """Implements the internals of pytest_runtest_xxx() hook."""
-        with catching_logs(LogCaptureHandler(),
-                           formatter=self.formatter) as log_handler:
+        with catching_logs(
+            LogCaptureHandler(), formatter=self.formatter, level=self.log_level
+        ) as log_handler:
+            if self.log_cli_handler:
+                self.log_cli_handler.set_when(when)
+
+            if item is None:
+                yield  # run the test
+                return
+
+            if not hasattr(item, "catch_log_handlers"):
+                item.catch_log_handlers = {}
+            item.catch_log_handlers[when] = log_handler
             item.catch_log_handler = log_handler
             try:
                 yield  # run test
             finally:
                 del item.catch_log_handler
+                if when == "teardown":
+                    del item.catch_log_handlers
 
             if self.print_logs:
                 # Add a captured log section to the report.
                 log = log_handler.stream.getvalue().strip()
-                item.add_report_section(when, 'log', log)
+                item.add_report_section(when, "log", log)
 
     @pytest.hookimpl(hookwrapper=True)
     def pytest_runtest_setup(self, item):
-        with self._runtest_for(item, 'setup'):
+        with self._runtest_for(item, "setup"):
             yield
 
     @pytest.hookimpl(hookwrapper=True)
     def pytest_runtest_call(self, item):
-        with self._runtest_for(item, 'call'):
+        with self._runtest_for(item, "call"):
             yield
 
     @pytest.hookimpl(hookwrapper=True)
     def pytest_runtest_teardown(self, item):
-        with self._runtest_for(item, 'teardown'):
+        with self._runtest_for(item, "teardown"):
+            yield
+
+    @pytest.hookimpl(hookwrapper=True)
+    def pytest_runtest_logstart(self):
+        if self.log_cli_handler:
+            self.log_cli_handler.reset()
+        with self._runtest_for(None, "start"):
+            yield
+
+    @pytest.hookimpl(hookwrapper=True)
+    def pytest_runtest_logfinish(self):
+        with self._runtest_for(None, "finish"):
             yield
 
     @pytest.hookimpl(hookwrapper=True)
     def pytest_runtestloop(self, session):
         """Runs all collected test items."""
-        with self.live_logs:
+        self._setup_cli_logging()
+        with self.live_logs_context:
             if self.log_file_handler is not None:
                 with closing(self.log_file_handler):
-                    with catching_logs(self.log_file_handler,
-                                       level=self.log_file_level):
+                    with catching_logs(
+                        self.log_file_handler, level=self.log_file_level
+                    ):
                         yield  # run all the tests
             else:
                 yield  # run all the tests
+
+    def _setup_cli_logging(self):
+        """Sets up the handler and logger for the Live Logs feature, if enabled.
+
+        This must be done right before starting the loop so we can access the terminal reporter plugin.
+        """
+        terminal_reporter = self._config.pluginmanager.get_plugin("terminalreporter")
+        if self._log_cli_enabled() and terminal_reporter is not None:
+            capture_manager = self._config.pluginmanager.get_plugin("capturemanager")
+            log_cli_handler = _LiveLoggingStreamHandler(
+                terminal_reporter, capture_manager
+            )
+            log_cli_format = get_option_ini(
+                self._config, "log_cli_format", "log_format"
+            )
+            log_cli_date_format = get_option_ini(
+                self._config, "log_cli_date_format", "log_date_format"
+            )
+            if (
+                self._config.option.color != "no"
+                and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search(log_cli_format)
+            ):
+                log_cli_formatter = ColoredLevelFormatter(
+                    create_terminal_writer(self._config),
+                    log_cli_format,
+                    datefmt=log_cli_date_format,
+                )
+            else:
+                log_cli_formatter = logging.Formatter(
+                    log_cli_format, datefmt=log_cli_date_format
+                )
+            log_cli_level = get_actual_log_level(
+                self._config, "log_cli_level", "log_level"
+            )
+            self.log_cli_handler = log_cli_handler
+            self.live_logs_context = catching_logs(
+                log_cli_handler, formatter=log_cli_formatter, level=log_cli_level
+            )
+        else:
+            self.live_logs_context = _dummy_context_manager()
+
+
+class _LiveLoggingStreamHandler(logging.StreamHandler):
+    """
+    Custom StreamHandler used by the live logging feature: it will write a newline before the first log message
+    in each test.
+
+    During live logging we must also explicitly disable stdout/stderr capturing otherwise it will get captured
+    and won't appear in the terminal.
+    """
+
+    def __init__(self, terminal_reporter, capture_manager):
+        """
+        :param _pytest.terminal.TerminalReporter terminal_reporter:
+        :param _pytest.capture.CaptureManager capture_manager:
+        """
+        logging.StreamHandler.__init__(self, stream=terminal_reporter)
+        self.capture_manager = capture_manager
+        self.reset()
+        self.set_when(None)
+        self._test_outcome_written = False
+
+    def reset(self):
+        """Reset the handler; should be called before the start of each test"""
+        self._first_record_emitted = False
+
+    def set_when(self, when):
+        """Prepares for the given test phase (setup/call/teardown)"""
+        self._when = when
+        self._section_name_shown = False
+        if when == "start":
+            self._test_outcome_written = False
+
+    def emit(self, record):
+        if self.capture_manager is not None:
+            self.capture_manager.suspend_global_capture()
+        try:
+            if not self._first_record_emitted:
+                self.stream.write("\n")
+                self._first_record_emitted = True
+            elif self._when in ("teardown", "finish"):
+                if not self._test_outcome_written:
+                    self._test_outcome_written = True
+                    self.stream.write("\n")
+            if not self._section_name_shown and self._when:
+                self.stream.section("live log " + self._when, sep="-", bold=True)
+                self._section_name_shown = True
+            logging.StreamHandler.emit(self, record)
+        finally:
+            if self.capture_manager is not None:
+                self.capture_manager.resume_global_capture()
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/main.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/main.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/main.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/main.py
@@ -1,97 +1,172 @@
 """ core implementation of testing process: init, session, runtest loop. """
 from __future__ import absolute_import, division, print_function
 
+import contextlib
 import functools
 import os
+import pkgutil
 import six
 import sys
 
 import _pytest
 from _pytest import nodes
 import _pytest._code
 import py
-try:
-    from collections import MutableMapping as MappingMixin
-except ImportError:
-    from UserDict import DictMixin as MappingMixin
 
 from _pytest.config import directory_arg, UsageError, hookimpl
 from _pytest.outcomes import exit
 from _pytest.runner import collect_one_node
 
-tracebackcutdir = py.path.local(_pytest.__file__).dirpath()
 
 # exitcodes for the command line
 EXIT_OK = 0
 EXIT_TESTSFAILED = 1
 EXIT_INTERRUPTED = 2
 EXIT_INTERNALERROR = 3
 EXIT_USAGEERROR = 4
 EXIT_NOTESTSCOLLECTED = 5
 
 
 def pytest_addoption(parser):
-    parser.addini("norecursedirs", "directory patterns to avoid for recursion",
-                  type="args", default=['.*', 'build', 'dist', 'CVS', '_darcs', '{arch}', '*.egg', 'venv'])
-    parser.addini("testpaths", "directories to search for tests when no files or directories are given in the "
-                               "command line.",
-                  type="args", default=[])
+    parser.addini(
+        "norecursedirs",
+        "directory patterns to avoid for recursion",
+        type="args",
+        default=[".*", "build", "dist", "CVS", "_darcs", "{arch}", "*.egg", "venv"],
+    )
+    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_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,
-                     help="exit after first num failures or errors.")
-    group._addoption('--strict', action="store_true",
-                     help="marks not registered in configuration file raise 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._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,
+        help="exit after first num failures or errors.",
+    )
+    group._addoption(
+        "--strict",
+        action="store_true",
+        help="marks not registered in configuration file raise 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._addoption(
+        "--rootdir",
+        action="store",
+        dest="rootdir",
+        help="Define root directory for tests. Can be relative path: 'root_dir', './root_dir', "
+        "'root_dir/another_dir/'; absolute path: '/home/user/root_dir'; path with variables: "
+        "'$HOME/root_dir'.",
+    )
 
     group = parser.getgroup("collect", "collection")
-    group.addoption('--collectonly', '--collect-only', action="store_true",
-                    help="only collect tests, don't execute them."),
-    group.addoption('--pyargs', action="store_true",
-                    help="try to interpret all arguments as python packages.")
-    group.addoption("--ignore", action="append", metavar="path",
-                    help="ignore path during collection (multi-allowed).")
+    group.addoption(
+        "--collectonly",
+        "--collect-only",
+        action="store_true",
+        help="only collect tests, don't execute them.",
+    ),
+    group.addoption(
+        "--pyargs",
+        action="store_true",
+        help="try to interpret all arguments as python packages.",
+    )
+    group.addoption(
+        "--ignore",
+        action="append",
+        metavar="path",
+        help="ignore path during collection (multi-allowed).",
+    )
+    group.addoption(
+        "--deselect",
+        action="append",
+        metavar="nodeid_prefix",
+        help="deselect item during collection (multi-allowed).",
+    )
     # when changing this to --conf-cut-dir, config.py Conftest.setinitial
     # needs upgrading as well
-    group.addoption('--confcutdir', dest="confcutdir", default=None,
-                    metavar="dir", type=functools.partial(directory_arg, optname="--confcutdir"),
-                    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.addoption('--collect-in-virtualenv', action='store_true',
-                    dest='collect_in_virtualenv', default=False,
-                    help="Don't ignore tests in a local virtualenv directory")
+    group.addoption(
+        "--confcutdir",
+        dest="confcutdir",
+        default=None,
+        metavar="dir",
+        type=functools.partial(directory_arg, optname="--confcutdir"),
+        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.addoption(
+        "--collect-in-virtualenv",
+        action="store_true",
+        dest="collect_in_virtualenv",
+        default=False,
+        help="Don't ignore tests in a local virtualenv directory",
+    )
 
-    group = parser.getgroup("debugconfig",
-                            "test session debugging and configuration")
-    group.addoption('--basetemp', dest="basetemp", default=None, metavar="dir",
-                    help="base temporary directory for this test run.")
+    group = parser.getgroup("debugconfig", "test session debugging and configuration")
+    group.addoption(
+        "--basetemp",
+        dest="basetemp",
+        default=None,
+        metavar="dir",
+        help="base temporary directory for this test run.",
+    )
 
 
 def pytest_configure(config):
-    __import__('pytest').config = config  # compatibiltiy
+    __import__("pytest").config = config  # compatibility
 
 
 def wrap_session(config, doit):
     """Skeleton command line program"""
     session = Session(config)
     session.exitstatus = EXIT_OK
     initstate = 0
     try:
@@ -103,34 +178,33 @@ def wrap_session(config, doit):
             session.exitstatus = doit(config, session) or 0
         except UsageError:
             raise
         except Failed:
             session.exitstatus = EXIT_TESTSFAILED
         except KeyboardInterrupt:
             excinfo = _pytest._code.ExceptionInfo()
             if initstate < 2 and isinstance(excinfo.value, exit.Exception):
-                sys.stderr.write('{0}: {1}\n'.format(
-                    excinfo.typename, excinfo.value.msg))
+                sys.stderr.write("{}: {}\n".format(excinfo.typename, excinfo.value.msg))
             config.hook.pytest_keyboard_interrupt(excinfo=excinfo)
             session.exitstatus = EXIT_INTERRUPTED
         except:  # noqa
             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")
 
     finally:
         excinfo = None  # Explicitly break reference cycle.
         session.startdir.chdir()
         if initstate >= 2:
             config.hook.pytest_sessionfinish(
-                session=session,
-                exitstatus=session.exitstatus)
+                session=session, exitstatus=session.exitstatus
+            )
         config._ensure_unconfigure()
     return session.exitstatus
 
 
 def pytest_cmdline_main(config):
     return wrap_session(config, _main)
 
 
@@ -146,20 +220,18 @@ def _main(config, session):
         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.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
 
     for i, item in enumerate(session.items):
         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.shouldfail:
@@ -167,21 +239,27 @@ def pytest_runtestloop(session):
         if session.shouldstop:
             raise session.Interrupted(session.shouldstop)
     return True
 
 
 def _in_venv(path):
     """Attempts to detect if ``path`` is the root of a Virtual Environment by
     checking for the existence of the appropriate activate script"""
-    bindir = path.join('Scripts' if sys.platform.startswith('win') else 'bin')
-    if not bindir.exists():
+    bindir = path.join("Scripts" if sys.platform.startswith("win") else "bin")
+    if not bindir.isdir():
         return False
-    activates = ('activate', 'activate.csh', 'activate.fish',
-                 'Activate', 'Activate.bat', 'Activate.ps1')
+    activates = (
+        "activate",
+        "activate.csh",
+        "activate.fish",
+        "Activate",
+        "Activate.bat",
+        "Activate.ps1",
+    )
     return any([fname.basename in activates for fname in bindir.listdir()])
 
 
 def pytest_ignore_collect(path, config):
     ignore_paths = config._getconftest_pathlist("collect_ignore", path=path.dirpath())
     ignore_paths = ignore_paths or []
     excludeopt = config.getoption("ignore")
     if excludeopt:
@@ -201,451 +279,160 @@ def pytest_ignore_collect(path, config):
         if path in duplicate_paths:
             return True
         else:
             duplicate_paths.add(path)
 
     return False
 
 
-class FSHookProxy:
+def pytest_collection_modifyitems(items, config):
+    deselect_prefixes = tuple(config.getoption("deselect") or [])
+    if not deselect_prefixes:
+        return
+
+    remaining = []
+    deselected = []
+    for colitem in items:
+        if colitem.nodeid.startswith(deselect_prefixes):
+            deselected.append(colitem)
+        else:
+            remaining.append(colitem)
+
+    if deselected:
+        config.hook.pytest_deselected(items=deselected)
+        items[:] = remaining
+
+
+@contextlib.contextmanager
+def _patched_find_module():
+    """Patch bug in pkgutil.ImpImporter.find_module
+
+    When using pkgutil.find_loader on python<3.4 it removes symlinks
+    from the path due to a call to os.path.realpath. This is not consistent
+    with actually doing the import (in these versions, pkgutil and __import__
+    did not share the same underlying code). This can break conftest
+    discovery for pytest where symlinks are involved.
+
+    The only supported python<3.4 by pytest is python 2.7.
+    """
+    if six.PY2:  # python 3.4+ uses importlib instead
+
+        def find_module_patched(self, fullname, path=None):
+            # Note: we ignore 'path' argument since it is only used via meta_path
+            subname = fullname.split(".")[-1]
+            if subname != fullname and self.path is None:
+                return None
+            if self.path is None:
+                path = None
+            else:
+                # original: path = [os.path.realpath(self.path)]
+                path = [self.path]
+            try:
+                file, filename, etc = pkgutil.imp.find_module(subname, path)
+            except ImportError:
+                return None
+            return pkgutil.ImpLoader(fullname, file, filename, etc)
+
+        old_find_module = pkgutil.ImpImporter.find_module
+        pkgutil.ImpImporter.find_module = find_module_patched
+        try:
+            yield
+        finally:
+            pkgutil.ImpImporter.find_module = old_find_module
+    else:
+        yield
+
+
+class FSHookProxy(object):
+
     def __init__(self, fspath, pm, remove_mods):
         self.fspath = fspath
         self.pm = pm
         self.remove_mods = remove_mods
 
     def __getattr__(self, name):
         x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods)
         self.__dict__[name] = x
         return x
 
 
-class _CompatProperty(object):
-    def __init__(self, name):
-        self.name = name
-
-    def __get__(self, obj, owner):
-        if obj is None:
-            return self
-
-        # TODO: reenable in the features branch
-        # warnings.warn(
-        #     "usage of {owner!r}.{name} is deprecated, please use pytest.{name} instead".format(
-        #         name=self.name, owner=type(owner).__name__),
-        #     PendingDeprecationWarning, stacklevel=2)
-        return getattr(__import__('pytest'), self.name)
-
-
-class NodeKeywords(MappingMixin):
-    def __init__(self, node):
-        self.node = node
-        self.parent = node.parent
-        self._markers = {node.name: True}
-
-    def __getitem__(self, key):
-        try:
-            return self._markers[key]
-        except KeyError:
-            if self.parent is None:
-                raise
-            return self.parent.keywords[key]
-
-    def __setitem__(self, key, value):
-        self._markers[key] = value
-
-    def __delitem__(self, key):
-        raise ValueError("cannot delete key in keywords dict")
-
-    def __iter__(self):
-        seen = set(self._markers)
-        if self.parent is not None:
-            seen.update(self.parent.keywords)
-        return iter(seen)
-
-    def __len__(self):
-        return len(self.__iter__())
-
-    def keys(self):
-        return list(self)
-
-    def __repr__(self):
-        return "<NodeKeywords for node %s>" % (self.node, )
-
-
-class Node(object):
-    """ base class for Collector and Item the test collection tree.
-    Collector subclasses have children, Items are terminal nodes."""
-
-    def __init__(self, name, parent=None, config=None, session=None):
-        #: a unique name within the scope of the parent node
-        self.name = name
-
-        #: the parent collector node.
-        self.parent = parent
-
-        #: the pytest config object
-        self.config = config or parent.config
-
-        #: the session this node is part of
-        self.session = session or parent.session
-
-        #: filesystem path where this node was collected from (can be None)
-        self.fspath = getattr(parent, 'fspath', None)
-
-        #: keywords/markers collected from all scopes
-        self.keywords = NodeKeywords(self)
-
-        #: allow adding of extra keywords to use for matching
-        self.extra_keyword_matches = set()
-
-        # used for storing artificial fixturedefs for direct parametrization
-        self._name2pseudofixturedef = {}
-
-    @property
-    def ihook(self):
-        """ fspath sensitive hook proxy used to call pytest hooks"""
-        return self.session.gethookproxy(self.fspath)
-
-    Module = _CompatProperty("Module")
-    Class = _CompatProperty("Class")
-    Instance = _CompatProperty("Instance")
-    Function = _CompatProperty("Function")
-    File = _CompatProperty("File")
-    Item = _CompatProperty("Item")
-
-    def _getcustomclass(self, name):
-        maybe_compatprop = getattr(type(self), name)
-        if isinstance(maybe_compatprop, _CompatProperty):
-            return getattr(__import__('pytest'), name)
-        else:
-            cls = getattr(self, name)
-            # TODO: reenable in the features branch
-            # warnings.warn("use of node.%s is deprecated, "
-            #    "use pytest_pycollect_makeitem(...) to create custom "
-            #    "collection nodes" % name, category=DeprecationWarning)
-        return cls
-
-    def __repr__(self):
-        return "<%s %r>" % (self.__class__.__name__,
-                            getattr(self, 'name', None))
-
-    def warn(self, code, message):
-        """ generate a warning with the given code and message for this
-        item. """
-        assert isinstance(code, str)
-        fslocation = getattr(self, "location", None)
-        if fslocation is None:
-            fslocation = getattr(self, "fspath", None)
-        self.ihook.pytest_logwarning.call_historic(kwargs=dict(
-            code=code, message=message,
-            nodeid=self.nodeid, fslocation=fslocation))
-
-    # methods for ordering nodes
-    @property
-    def nodeid(self):
-        """ a ::-separated string denoting its collection tree address. """
-        try:
-            return self._nodeid
-        except AttributeError:
-            self._nodeid = x = self._makeid()
-            return x
-
-    def _makeid(self):
-        return self.parent.nodeid + "::" + self.name
-
-    def __hash__(self):
-        return hash(self.nodeid)
-
-    def setup(self):
-        pass
-
-    def teardown(self):
-        pass
-
-    def listchain(self):
-        """ return list of all parent collectors up to self,
-            starting from root of collection tree. """
-        chain = []
-        item = self
-        while item is not None:
-            chain.append(item)
-            item = item.parent
-        chain.reverse()
-        return chain
-
-    def add_marker(self, marker):
-        """ dynamically add a marker object to the node.
-
-        ``marker`` can be a string or pytest.mark.* instance.
-        """
-        from _pytest.mark import MarkDecorator, MARK_GEN
-        if isinstance(marker, six.string_types):
-            marker = getattr(MARK_GEN, marker)
-        elif not isinstance(marker, MarkDecorator):
-            raise ValueError("is not a string or pytest.mark.* Marker")
-        self.keywords[marker.name] = marker
-
-    def get_marker(self, name):
-        """ get a marker object from this node or None if
-        the node doesn't have a marker with that name. """
-        val = self.keywords.get(name, None)
-        if val is not None:
-            from _pytest.mark import MarkInfo, MarkDecorator
-            if isinstance(val, (MarkDecorator, MarkInfo)):
-                return val
-
-    def listextrakeywords(self):
-        """ Return a set of all extra keywords in self and any parents."""
-        extra_keywords = set()
-        item = self
-        for item in self.listchain():
-            extra_keywords.update(item.extra_keyword_matches)
-        return extra_keywords
-
-    def listnames(self):
-        return [x.name for x in self.listchain()]
-
-    def addfinalizer(self, fin):
-        """ register a function to be called when this node is finalized.
-
-        This method can only be called when this node is active
-        in a setup chain, for example during self.setup().
-        """
-        self.session._setupstate.addfinalizer(fin, self)
-
-    def getparent(self, cls):
-        """ get the next parent node (including ourself)
-        which is an instance of the given class"""
-        current = self
-        while current and not isinstance(current, cls):
-            current = current.parent
-        return current
-
-    def _prunetraceback(self, excinfo):
-        pass
-
-    def _repr_failure_py(self, excinfo, style=None):
-        fm = self.session._fixturemanager
-        if excinfo.errisinstance(fm.FixtureLookupError):
-            return excinfo.value.formatrepr()
-        tbfilter = True
-        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"
-        # XXX should excinfo.getrepr record all data and toterminal() process it?
-        if style is None:
-            if self.config.option.tbstyle == "short":
-                style = "short"
-            else:
-                style = "long"
-
-        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)
-
-    repr_failure = _repr_failure_py
-
-
-class Collector(Node):
-    """ Collector instances create children through collect()
-        and thus iteratively build a tree.
-    """
-
-    class CollectError(Exception):
-        """ an error during collection, contains a custom message. """
-
-    def collect(self):
-        """ returns a list of children (items and collectors)
-            for this collection node.
-        """
-        raise NotImplementedError("abstract")
-
-    def repr_failure(self, excinfo):
-        """ represent a collection failure. """
-        if excinfo.errisinstance(self.CollectError):
-            exc = excinfo.value
-            return str(exc.args[0])
-        return self._repr_failure_py(excinfo, style="short")
-
-    def _prunetraceback(self, excinfo):
-        if hasattr(self, 'fspath'):
-            traceback = excinfo.traceback
-            ntraceback = traceback.cut(path=self.fspath)
-            if ntraceback == traceback:
-                ntraceback = ntraceback.cut(excludepath=tracebackcutdir)
-            excinfo.traceback = ntraceback.filter()
-
-
-class FSCollector(Collector):
-    def __init__(self, fspath, parent=None, config=None, session=None):
-        fspath = py.path.local(fspath)  # xxx only for test_resultlog.py?
-        name = fspath.basename
-        if parent is not None:
-            rel = fspath.relto(parent.fspath)
-            if rel:
-                name = rel
-            name = name.replace(os.sep, nodes.SEP)
-        super(FSCollector, self).__init__(name, parent, config, session)
-        self.fspath = fspath
-
-    def _check_initialpaths_for_relpath(self):
-        for initialpath in self.session._initialpaths:
-            if self.fspath.common(initialpath) == initialpath:
-                return self.fspath.relto(initialpath.dirname)
-
-    def _makeid(self):
-        relpath = self.fspath.relto(self.config.rootdir)
-
-        if not relpath:
-            relpath = self._check_initialpaths_for_relpath()
-        if os.sep != nodes.SEP:
-            relpath = relpath.replace(os.sep, nodes.SEP)
-        return relpath
-
-
-class File(FSCollector):
-    """ base class for collecting tests from a file. """
-
-
-class Item(Node):
-    """ a basic test invocation item. Note that for a single function
-    there might be multiple test invocation items.
-    """
-    nextitem = None
-
-    def __init__(self, name, parent=None, config=None, session=None):
-        super(Item, self).__init__(name, parent, config, session)
-        self._report_sections = []
-
-    def add_report_section(self, when, key, content):
-        """
-        Adds a new report section, similar to what's done internally to add stdout and
-        stderr captured output::
-
-            item.add_report_section("call", "stdout", "report section contents")
-
-        :param str when:
-            One of the possible capture states, ``"setup"``, ``"call"``, ``"teardown"``.
-        :param str key:
-            Name of the section, can be customized at will. Pytest uses ``"stdout"`` and
-            ``"stderr"`` internally.
-
-        :param str content:
-            The full contents as a string.
-        """
-        if content:
-            self._report_sections.append((when, key, content))
-
-    def reportinfo(self):
-        return self.fspath, None, ""
-
-    @property
-    def location(self):
-        try:
-            return self._location
-        except AttributeError:
-            location = self.reportinfo()
-            # bestrelpath is a quite slow function
-            cache = self.config.__dict__.setdefault("_bestrelpathcache", {})
-            try:
-                fspath = cache[location[0]]
-            except KeyError:
-                fspath = self.session.fspath.bestrelpath(location[0])
-                cache[location[0]] = fspath
-            location = (fspath, location[1], str(location[2]))
-            self._location = location
-            return location
-
-
 class NoMatch(Exception):
     """ raised if matching cannot locate a matching names. """
 
 
 class Interrupted(KeyboardInterrupt):
     """ signals an interrupted test run. """
-    __module__ = 'builtins'  # for py3
+    __module__ = "builtins"  # for py3
 
 
 class Failed(Exception):
-    """ signals an stop as failed test run. """
+    """ signals a stop as failed test run. """
 
 
-class Session(FSCollector):
+class Session(nodes.FSCollector):
     Interrupted = Interrupted
     Failed = Failed
 
     def __init__(self, config):
-        FSCollector.__init__(self, config.rootdir, parent=None,
-                             config=config, session=self)
+        nodes.FSCollector.__init__(
+            self, config.rootdir, parent=None, config=config, session=self, nodeid=""
+        )
         self.testsfailed = 0
         self.testscollected = 0
         self.shouldstop = False
         self.shouldfail = False
         self.trace = config.trace.root.get("collection")
         self._norecursepatterns = config.getini("norecursedirs")
         self.startdir = py.path.local()
+
         self.config.pluginmanager.register(self, name="session")
 
-    def _makeid(self):
-        return ""
-
     @hookimpl(tryfirst=True)
     def pytest_collectstart(self):
         if self.shouldfail:
             raise self.Failed(self.shouldfail)
         if self.shouldstop:
             raise self.Interrupted(self.shouldstop)
 
     @hookimpl(tryfirst=True)
     def pytest_runtest_logreport(self, report):
-        if report.failed and not hasattr(report, 'wasxfail'):
+        if report.failed and not hasattr(report, "wasxfail"):
             self.testsfailed += 1
             maxfail = self.config.getvalue("maxfail")
             if maxfail and self.testsfailed >= maxfail:
-                self.shouldfail = "stopping after %d failures" % (
-                    self.testsfailed)
+                self.shouldfail = "stopping after %d failures" % (self.testsfailed)
+
     pytest_collectreport = pytest_runtest_logreport
 
     def isinitpath(self, path):
         return path in self._initialpaths
 
     def gethookproxy(self, fspath):
         # check if we have the common case of running
-        # hooks with all conftest.py filesall conftest.py
+        # hooks with all conftest.py files
         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
         return proxy
 
     def perform_collect(self, args=None, genitems=True):
         hook = self.config.hook
         try:
             items = self._perform_collect(args, genitems)
             self.config.pluginmanager.check_pending()
-            hook.pytest_collection_modifyitems(session=self,
-                                               config=self.config, items=items)
+            hook.pytest_collection_modifyitems(
+                session=self, config=self.config, items=items
+            )
         finally:
             hook.pytest_collection_finish(session=self)
         self.testscollected = len(items)
         return items
 
     def _perform_collect(self, args, genitems):
         if args is None:
             args = self.config.args
@@ -692,18 +479,19 @@ class Session(FSCollector):
 
             self.trace.root.indent -= 1
 
     def _collect(self, arg):
         names = self._parsearg(arg)
         path = names.pop(0)
         if path.check(dir=1):
             assert not names, "invalid arg %r" % (arg,)
-            for path in path.visit(fil=lambda x: x.check(file=1),
-                                   rec=self._recurse, bf=True, sort=True):
+            for path in path.visit(
+                fil=lambda x: x.check(file=1), rec=self._recurse, bf=True, sort=True
+            ):
                 for x in self._collectfile(path):
                     yield x
         else:
             assert path.check(file=1)
             for x in self.matchnodes(self._collectfile(path), names):
                 yield x
 
     def _collectfile(self, path):
@@ -723,27 +511,29 @@ class Session(FSCollector):
         ihook = self.gethookproxy(path)
         ihook.pytest_collect_directory(path=path, parent=self)
         return True
 
     def _tryconvertpyarg(self, x):
         """Convert a dotted module name to path.
 
         """
-        import pkgutil
+
         try:
-            loader = pkgutil.find_loader(x)
+            with _patched_find_module():
+                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)
+            with _patched_find_module():
+                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):
@@ -751,18 +541,18 @@ class Session(FSCollector):
         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():
             if self.config.option.pyargs:
                 raise UsageError(
-                    "file or package not found: " + arg +
-                    " (missing __init__.py?)")
+                    "file or package not found: " + arg + " (missing __init__.py?)"
+                )
             else:
                 raise UsageError("file not found: " + arg)
         parts[0] = path
         return parts
 
     def matchnodes(self, matching, names):
         self.trace("matchnodes", matching, names)
         self.trace.root.indent += 1
@@ -777,21 +567,21 @@ class Session(FSCollector):
     def _matchnodes(self, matching, names):
         if not matching or not names:
             return matching
         name = names[0]
         assert name
         nextnames = names[1:]
         resultnodes = []
         for node in matching:
-            if isinstance(node, Item):
+            if isinstance(node, nodes.Item):
                 if not names:
                     resultnodes.append(node)
                 continue
-            assert isinstance(node, Collector)
+            assert isinstance(node, nodes.Collector)
             rep = collect_one_node(node)
             if rep.passed:
                 has_matched = False
                 for x in rep.result:
                     # 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
@@ -803,19 +593,19 @@ class Session(FSCollector):
                 # report collection failures here to avoid failing to run some test
                 # specified in the command line because the module could not be
                 # imported (#134)
                 node.ihook.pytest_collectreport(report=rep)
         return resultnodes
 
     def genitems(self, node):
         self.trace("genitems", node)
-        if isinstance(node, Item):
+        if isinstance(node, nodes.Item):
             node.ihook.pytest_itemcollected(item=node)
             yield node
         else:
-            assert isinstance(node, Collector)
+            assert isinstance(node, nodes.Collector)
             rep = collect_one_node(node)
             if rep.passed:
                 for subnode in rep.result:
                     for x in self.genitems(subnode):
                         yield x
             node.ihook.pytest_collectreport(report=rep)
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/mark/__init__.py
@@ -0,0 +1,174 @@
+""" generic mechanism for marking and selecting python functions. """
+from __future__ import absolute_import, division, print_function
+from _pytest.config import UsageError
+from .structures import (
+    ParameterSet,
+    EMPTY_PARAMETERSET_OPTION,
+    MARK_GEN,
+    Mark,
+    MarkInfo,
+    MarkDecorator,
+    MarkGenerator,
+    transfer_markers,
+    get_empty_parameterset_mark,
+)
+from .legacy import matchkeyword, matchmark
+
+__all__ = [
+    "Mark",
+    "MarkInfo",
+    "MarkDecorator",
+    "MarkGenerator",
+    "transfer_markers",
+    "get_empty_parameterset_mark",
+]
+
+
+class MarkerError(Exception):
+
+    """Error in use of a pytest marker/attribute."""
+
+
+def param(*values, **kw):
+    """Specify a parameter in `pytest.mark.parametrize`_ calls or
+    :ref:`parametrized fixtures <fixture-parametrize-marks>`.
+
+    .. code-block:: python
+
+        @pytest.mark.parametrize("test_input,expected", [
+            ("3+5", 8),
+            pytest.param("6*9", 42, marks=pytest.mark.xfail),
+        ])
+        def test_eval(test_input, expected):
+            assert eval(test_input) == expected
+
+    :param values: variable args of the values of the parameter set, in order.
+    :keyword marks: a single mark or a list of marks to be applied to this parameter set.
+    :keyword str id: the id to attribute to this parameter set.
+    """
+    return ParameterSet.param(*values, **kw)
+
+
+def pytest_addoption(parser):
+    group = parser.getgroup("general")
+    group._addoption(
+        "-k",
+        action="store",
+        dest="keyword",
+        default="",
+        metavar="EXPRESSION",
+        help="only run tests which match the given substring expression. "
+        "An expression is a python evaluatable expression "
+        "where all names are substring-matched against test names "
+        "and their parent classes. Example: -k 'test_method or test_"
+        "other' matches all test functions and classes whose name "
+        "contains 'test_method' or 'test_other', while -k 'not test_method' "
+        "matches those that don't contain 'test_method' in their names. "
+        "Additionally keywords are matched to classes and functions "
+        "containing extra names in their 'extra_keyword_matches' set, "
+        "as well as functions which have names assigned directly to them.",
+    )
+
+    group._addoption(
+        "-m",
+        action="store",
+        dest="markexpr",
+        default="",
+        metavar="MARKEXPR",
+        help="only run tests matching given mark expression.  "
+        "example: -m 'mark1 and not mark2'.",
+    )
+
+    group.addoption(
+        "--markers",
+        action="store_true",
+        help="show markers (builtin, plugin and per-project ones).",
+    )
+
+    parser.addini("markers", "markers for test functions", "linelist")
+    parser.addini(EMPTY_PARAMETERSET_OPTION, "default marker for empty parametersets")
+
+
+def pytest_cmdline_main(config):
+    import _pytest.config
+
+    if config.option.markers:
+        config._do_configure()
+        tw = _pytest.config.create_terminal_writer(config)
+        for line in config.getini("markers"):
+            parts = line.split(":", 1)
+            name = parts[0]
+            rest = parts[1] if len(parts) == 2 else ""
+            tw.write("@pytest.mark.%s:" % name, bold=True)
+            tw.line(rest)
+            tw.line()
+        config._ensure_unconfigure()
+        return 0
+
+
+pytest_cmdline_main.tryfirst = True
+
+
+def deselect_by_keyword(items, config):
+    keywordexpr = config.option.keyword.lstrip()
+    if keywordexpr.startswith("-"):
+        keywordexpr = "not " + keywordexpr[1:]
+    selectuntil = False
+    if keywordexpr[-1:] == ":":
+        selectuntil = True
+        keywordexpr = keywordexpr[:-1]
+
+    remaining = []
+    deselected = []
+    for colitem in items:
+        if keywordexpr and not matchkeyword(colitem, keywordexpr):
+            deselected.append(colitem)
+        else:
+            if selectuntil:
+                keywordexpr = None
+            remaining.append(colitem)
+
+    if deselected:
+        config.hook.pytest_deselected(items=deselected)
+        items[:] = remaining
+
+
+def deselect_by_mark(items, config):
+    matchexpr = config.option.markexpr
+    if not matchexpr:
+        return
+
+    remaining = []
+    deselected = []
+    for item in items:
+        if matchmark(item, matchexpr):
+            remaining.append(item)
+        else:
+            deselected.append(item)
+
+    if deselected:
+        config.hook.pytest_deselected(items=deselected)
+        items[:] = remaining
+
+
+def pytest_collection_modifyitems(items, config):
+    deselect_by_keyword(items, config)
+    deselect_by_mark(items, config)
+
+
+def pytest_configure(config):
+    config._old_mark_config = MARK_GEN._config
+    if config.option.strict:
+        MARK_GEN._config = config
+
+    empty_parameterset = config.getini(EMPTY_PARAMETERSET_OPTION)
+
+    if empty_parameterset not in ("skip", "xfail", None, ""):
+        raise UsageError(
+            "{!s} must be one of skip and xfail,"
+            " but it is {!r}".format(EMPTY_PARAMETERSET_OPTION, empty_parameterset)
+        )
+
+
+def pytest_unconfigure(config):
+    MARK_GEN._config = getattr(config, "_old_mark_config", None)
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/mark/evaluate.py
@@ -0,0 +1,121 @@
+import os
+import six
+import sys
+import platform
+import traceback
+
+from ..outcomes import fail, TEST_OUTCOME
+
+
+def cached_eval(config, expr, d):
+    if not hasattr(config, "_evalcache"):
+        config._evalcache = {}
+    try:
+        return config._evalcache[expr]
+    except KeyError:
+        import _pytest._code
+
+        exprcode = _pytest._code.compile(expr, mode="eval")
+        config._evalcache[expr] = x = eval(exprcode, d)
+        return x
+
+
+class MarkEvaluator(object):
+
+    def __init__(self, item, name):
+        self.item = item
+        self._marks = None
+        self._mark = None
+        self._mark_name = name
+
+    def __bool__(self):
+        # dont cache here to prevent staleness
+        return bool(self._get_marks())
+
+    __nonzero__ = __bool__
+
+    def wasvalid(self):
+        return not hasattr(self, "exc")
+
+    def _get_marks(self):
+        return list(self.item.iter_markers(name=self._mark_name))
+
+    def invalidraise(self, exc):
+        raises = self.get("raises")
+        if not raises:
+            return
+        return not isinstance(exc, raises)
+
+    def istrue(self):
+        try:
+            return self._istrue()
+        except TEST_OUTCOME:
+            self.exc = sys.exc_info()
+            if isinstance(self.exc[1], SyntaxError):
+                msg = [" " * (self.exc[1].offset + 4) + "^"]
+                msg.append("SyntaxError: invalid syntax")
+            else:
+                msg = traceback.format_exception_only(*self.exc[:2])
+            fail(
+                "Error evaluating %r expression\n"
+                "    %s\n"
+                "%s" % (self._mark_name, self.expr, "\n".join(msg)),
+                pytrace=False,
+            )
+
+    def _getglobals(self):
+        d = {"os": os, "sys": sys, "platform": platform, "config": self.item.config}
+        if hasattr(self.item, "obj"):
+            d.update(self.item.obj.__globals__)
+        return d
+
+    def _istrue(self):
+        if hasattr(self, "result"):
+            return self.result
+        self._marks = self._get_marks()
+
+        if self._marks:
+            self.result = False
+            for mark in self._marks:
+                self._mark = mark
+                if "condition" in mark.kwargs:
+                    args = (mark.kwargs["condition"],)
+                else:
+                    args = mark.args
+
+                for expr in args:
+                    self.expr = expr
+                    if isinstance(expr, six.string_types):
+                        d = self._getglobals()
+                        result = cached_eval(self.item.config, expr, d)
+                    else:
+                        if "reason" not in mark.kwargs:
+                            # XXX better be checked at collection time
+                            msg = "you need to specify reason=STRING " "when using booleans as conditions."
+                            fail(msg)
+                        result = bool(expr)
+                    if result:
+                        self.result = True
+                        self.reason = mark.kwargs.get("reason", None)
+                        self.expr = expr
+                        return self.result
+
+                if not args:
+                    self.result = True
+                    self.reason = mark.kwargs.get("reason", None)
+                    return self.result
+        return False
+
+    def get(self, attr, default=None):
+        if self._mark is None:
+            return default
+        return self._mark.kwargs.get(attr, default)
+
+    def getexplanation(self):
+        expl = getattr(self, "reason", None) or self.get("reason", None)
+        if not expl:
+            if not hasattr(self, "expr"):
+                return ""
+            else:
+                return "condition: " + str(self.expr)
+        return expl
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/mark/legacy.py
@@ -0,0 +1,97 @@
+"""
+this is a place where we put datastructures used by legacy apis
+we hope ot remove
+"""
+import attr
+import keyword
+
+from _pytest.config import UsageError
+
+
+@attr.s
+class MarkMapping(object):
+    """Provides a local mapping for markers where item access
+    resolves to True if the marker is present. """
+
+    own_mark_names = attr.ib()
+
+    @classmethod
+    def from_item(cls, item):
+        mark_names = {mark.name for mark in item.iter_markers()}
+        return cls(mark_names)
+
+    def __getitem__(self, name):
+        return name in self.own_mark_names
+
+
+class KeywordMapping(object):
+    """Provides a local mapping for keywords.
+    Given a list of names, map any substring of one of these names to True.
+    """
+
+    def __init__(self, names):
+        self._names = names
+
+    @classmethod
+    def from_item(cls, item):
+        mapped_names = set()
+
+        # Add the names of the current item and any parent items
+        import pytest
+
+        for item in item.listchain():
+            if not isinstance(item, pytest.Instance):
+                mapped_names.add(item.name)
+
+        # Add the names added as extra keywords to current or parent items
+        for name in item.listextrakeywords():
+            mapped_names.add(name)
+
+        # Add the names attached to the current function through direct assignment
+        if hasattr(item, "function"):
+            for name in item.function.__dict__:
+                mapped_names.add(name)
+
+        return cls(mapped_names)
+
+    def __getitem__(self, subname):
+        for name in self._names:
+            if subname in name:
+                return True
+        return False
+
+
+python_keywords_allowed_list = ["or", "and", "not"]
+
+
+def matchmark(colitem, markexpr):
+    """Tries to match on any marker names, attached to the given colitem."""
+    return eval(markexpr, {}, MarkMapping.from_item(colitem))
+
+
+def matchkeyword(colitem, keywordexpr):
+    """Tries to match given keyword expression to given collector item.
+
+    Will match on the name of colitem, including the names of its parents.
+    Only matches names of items which are either a :class:`Class` or a
+    :class:`Function`.
+    Additionally, matches on names in the 'extra_keyword_matches' set of
+    any item, as well as names directly assigned to test functions.
+    """
+    mapping = KeywordMapping.from_item(colitem)
+    if " " not in keywordexpr:
+        # special case to allow for simple "-k pass" and "-k 1.3"
+        return mapping[keywordexpr]
+    elif keywordexpr.startswith("not ") and " " not in keywordexpr[4:]:
+        return not mapping[keywordexpr[4:]]
+    for kwd in keywordexpr.split():
+        if keyword.iskeyword(kwd) and kwd not in python_keywords_allowed_list:
+            raise UsageError(
+                "Python keyword '{}' not accepted in expressions passed to '-k'".format(
+                    kwd
+                )
+            )
+    try:
+        return eval(keywordexpr, {}, mapping)
+    except SyntaxError:
+        raise UsageError("Wrong expression passed to '-k': {}".format(keywordexpr))
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/mark/structures.py
@@ -0,0 +1,428 @@
+import inspect
+import warnings
+from collections import namedtuple
+from operator import attrgetter
+
+import attr
+
+from ..deprecated import MARK_PARAMETERSET_UNPACKING, MARK_INFO_ATTRIBUTE
+from ..compat import NOTSET, getfslineno, MappingMixin
+from six.moves import map, reduce
+
+
+EMPTY_PARAMETERSET_OPTION = "empty_parameter_set_mark"
+
+
+def alias(name, warning=None):
+    getter = attrgetter(name)
+
+    def warned(self):
+        warnings.warn(warning, stacklevel=2)
+        return getter(self)
+
+    return property(getter if warning is None else warned, doc="alias for " + name)
+
+
+def istestfunc(func):
+    return hasattr(func, "__call__") and getattr(
+        func, "__name__", "<lambda>"
+    ) != "<lambda>"
+
+
+def get_empty_parameterset_mark(config, argnames, func):
+    requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION)
+    if requested_mark in ("", None, "skip"):
+        mark = MARK_GEN.skip
+    elif requested_mark == "xfail":
+        mark = MARK_GEN.xfail(run=False)
+    else:
+        raise LookupError(requested_mark)
+    fs, lineno = getfslineno(func)
+    reason = "got empty parameter set %r, function %s at %s:%d" % (
+        argnames, func.__name__, fs, lineno
+    )
+    return mark(reason=reason)
+
+
+class ParameterSet(namedtuple("ParameterSet", "values, marks, id")):
+
+    @classmethod
+    def param(cls, *values, **kw):
+        marks = kw.pop("marks", ())
+        if isinstance(marks, MarkDecorator):
+            marks = marks,
+        else:
+            assert isinstance(marks, (tuple, list, set))
+
+        def param_extract_id(id=None):
+            return id
+
+        id_ = param_extract_id(**kw)
+        return cls(values, marks, id_)
+
+    @classmethod
+    def extract_from(cls, parameterset, legacy_force_tuple=False):
+        """
+        :param parameterset:
+            a legacy style parameterset that may or may not be a tuple,
+            and may or may not be wrapped into a mess of mark objects
+
+        :param legacy_force_tuple:
+            enforce tuple wrapping so single argument tuple values
+            don't get decomposed and break tests
+
+        """
+
+        if isinstance(parameterset, cls):
+            return parameterset
+        if not isinstance(parameterset, MarkDecorator) and legacy_force_tuple:
+            return cls.param(parameterset)
+
+        newmarks = []
+        argval = parameterset
+        while isinstance(argval, MarkDecorator):
+            newmarks.append(
+                MarkDecorator(Mark(argval.markname, argval.args[:-1], argval.kwargs))
+            )
+            argval = argval.args[-1]
+        assert not isinstance(argval, ParameterSet)
+        if legacy_force_tuple:
+            argval = argval,
+
+        if newmarks:
+            warnings.warn(MARK_PARAMETERSET_UNPACKING)
+
+        return cls(argval, marks=newmarks, id=None)
+
+    @classmethod
+    def _for_parametrize(cls, argnames, argvalues, func, config):
+        if not isinstance(argnames, (tuple, list)):
+            argnames = [x.strip() for x in argnames.split(",") if x.strip()]
+            force_tuple = len(argnames) == 1
+        else:
+            force_tuple = False
+        parameters = [
+            ParameterSet.extract_from(x, legacy_force_tuple=force_tuple)
+            for x in argvalues
+        ]
+        del argvalues
+
+        if not parameters:
+            mark = get_empty_parameterset_mark(config, argnames, func)
+            parameters.append(
+                ParameterSet(values=(NOTSET,) * len(argnames), marks=[mark], id=None)
+            )
+        return argnames, parameters
+
+
+@attr.s(frozen=True)
+class Mark(object):
+    #: name of the mark
+    name = attr.ib(type=str)
+    #: positional arguments of the mark decorator
+    args = attr.ib(type="List[object]")
+    #: keyword arguments of the mark decorator
+    kwargs = attr.ib(type="Dict[str, object]")
+
+    def combined_with(self, other):
+        """
+        :param other: the mark to combine with
+        :type other: Mark
+        :rtype: Mark
+
+        combines by appending aargs and merging the mappings
+        """
+        assert self.name == other.name
+        return Mark(
+            self.name, self.args + other.args, dict(self.kwargs, **other.kwargs)
+        )
+
+
+@attr.s
+class MarkDecorator(object):
+    """ A decorator for test functions and test classes.  When applied
+    it will create :class:`MarkInfo` objects which may be
+    :ref:`retrieved by hooks as item keywords <excontrolskip>`.
+    MarkDecorator instances are often created like this::
+
+        mark1 = pytest.mark.NAME              # simple MarkDecorator
+        mark2 = pytest.mark.NAME(name1=value) # parametrized MarkDecorator
+
+    and can then be applied as decorators to test functions::
+
+        @mark2
+        def test_function():
+            pass
+
+    When a MarkDecorator instance is called it does the following:
+      1. If called with a single class as its only positional argument and no
+         additional keyword arguments, it attaches itself to the class so it
+         gets applied automatically to all test cases found in that class.
+      2. If called with a single function as its only positional argument and
+         no additional keyword arguments, it attaches a MarkInfo object to the
+         function, containing all the arguments already stored internally in
+         the MarkDecorator.
+      3. When called in any other case, it performs a 'fake construction' call,
+         i.e. it returns a new MarkDecorator instance with the original
+         MarkDecorator's content updated with the arguments passed to this
+         call.
+
+    Note: The rules above prevent MarkDecorator objects from storing only a
+    single function or class reference as their positional argument with no
+    additional keyword or positional arguments.
+
+    """
+
+    mark = attr.ib(validator=attr.validators.instance_of(Mark))
+
+    name = alias("mark.name")
+    args = alias("mark.args")
+    kwargs = alias("mark.kwargs")
+
+    @property
+    def markname(self):
+        return self.name  # for backward-compat (2.4.1 had this attr)
+
+    def __eq__(self, other):
+        return self.mark == other.mark if isinstance(other, MarkDecorator) else False
+
+    def __repr__(self):
+        return "<MarkDecorator %r>" % (self.mark,)
+
+    def with_args(self, *args, **kwargs):
+        """ return a MarkDecorator with extra arguments added
+
+        unlike call this can be used even if the sole argument is a callable/class
+
+        :return: MarkDecorator
+        """
+
+        mark = Mark(self.name, args, kwargs)
+        return self.__class__(self.mark.combined_with(mark))
+
+    def __call__(self, *args, **kwargs):
+        """ if passed a single callable argument: decorate it with mark info.
+            otherwise add *args/**kwargs in-place to mark information. """
+        if args and not kwargs:
+            func = args[0]
+            is_class = inspect.isclass(func)
+            if len(args) == 1 and (istestfunc(func) or is_class):
+                if is_class:
+                    store_mark(func, self.mark)
+                else:
+                    store_legacy_markinfo(func, self.mark)
+                    store_mark(func, self.mark)
+                return func
+        return self.with_args(*args, **kwargs)
+
+
+def get_unpacked_marks(obj):
+    """
+    obtain the unpacked marks that are stored on an object
+    """
+    mark_list = getattr(obj, "pytestmark", [])
+
+    if not isinstance(mark_list, list):
+        mark_list = [mark_list]
+    return [getattr(mark, "mark", mark) for mark in mark_list]  # unpack MarkDecorator
+
+
+def store_mark(obj, mark):
+    """store a Mark on an object
+    this is used to implement the Mark declarations/decorators correctly
+    """
+    assert isinstance(mark, Mark), mark
+    # always reassign name to avoid updating pytestmark
+    # in a reference that was only borrowed
+    obj.pytestmark = get_unpacked_marks(obj) + [mark]
+
+
+def store_legacy_markinfo(func, mark):
+    """create the legacy MarkInfo objects and put them onto the function
+    """
+    if not isinstance(mark, Mark):
+        raise TypeError("got {mark!r} instead of a Mark".format(mark=mark))
+    holder = getattr(func, mark.name, None)
+    if holder is None:
+        holder = MarkInfo.for_mark(mark)
+        setattr(func, mark.name, holder)
+    else:
+        holder.add_mark(mark)
+
+
+def transfer_markers(funcobj, cls, mod):
+    """
+    this function transfers class level markers and module level markers
+    into function level markinfo objects
+
+    this is the main reason why marks are so broken
+    the resolution will involve phasing out function level MarkInfo objects
+
+    """
+    for obj in (cls, mod):
+        for mark in get_unpacked_marks(obj):
+            if not _marked(funcobj, mark):
+                store_legacy_markinfo(funcobj, mark)
+
+
+def _marked(func, mark):
+    """ Returns True if :func: is already marked with :mark:, False otherwise.
+    This can happen if marker is applied to class and the test file is
+    invoked more than once.
+    """
+    try:
+        func_mark = getattr(func, getattr(mark, "combined", mark).name)
+    except AttributeError:
+        return False
+    return any(mark == info.combined for info in func_mark)
+
+
+@attr.s
+class MarkInfo(object):
+    """ Marking object created by :class:`MarkDecorator` instances. """
+
+    _marks = attr.ib(convert=list)
+
+    @_marks.validator
+    def validate_marks(self, attribute, value):
+        for item in value:
+            if not isinstance(item, Mark):
+                raise ValueError(
+                    "MarkInfo expects Mark instances, got {!r} ({!r})".format(
+                        item, type(item)
+                    )
+                )
+
+    combined = attr.ib(
+        repr=False,
+        default=attr.Factory(
+            lambda self: reduce(Mark.combined_with, self._marks), takes_self=True
+        ),
+    )
+
+    name = alias("combined.name", warning=MARK_INFO_ATTRIBUTE)
+    args = alias("combined.args", warning=MARK_INFO_ATTRIBUTE)
+    kwargs = alias("combined.kwargs", warning=MARK_INFO_ATTRIBUTE)
+
+    @classmethod
+    def for_mark(cls, mark):
+        return cls([mark])
+
+    def __repr__(self):
+        return "<MarkInfo {!r}>".format(self.combined)
+
+    def add_mark(self, mark):
+        """ add a MarkInfo with the given args and kwargs. """
+        self._marks.append(mark)
+        self.combined = self.combined.combined_with(mark)
+
+    def __iter__(self):
+        """ yield MarkInfo objects each relating to a marking-call. """
+        return map(MarkInfo.for_mark, self._marks)
+
+
+class MarkGenerator(object):
+    """ Factory for :class:`MarkDecorator` objects - exposed as
+    a ``pytest.mark`` singleton instance.  Example::
+
+         import pytest
+         @pytest.mark.slowtest
+         def test_function():
+            pass
+
+    will set a 'slowtest' :class:`MarkInfo` object
+    on the ``test_function`` object. """
+    _config = None
+
+    def __getattr__(self, name):
+        if name[0] == "_":
+            raise AttributeError("Marker name must NOT start with underscore")
+        if self._config is not None:
+            self._check(name)
+        return MarkDecorator(Mark(name, (), {}))
+
+    def _check(self, name):
+        try:
+            if name in self._markers:
+                return
+        except AttributeError:
+            pass
+        self._markers = values = set()
+        for line in self._config.getini("markers"):
+            marker = line.split(":", 1)[0]
+            marker = marker.rstrip()
+            x = marker.split("(", 1)[0]
+            values.add(x)
+        if name not in self._markers:
+            raise AttributeError("%r not a registered marker" % (name,))
+
+
+MARK_GEN = MarkGenerator()
+
+
+class NodeKeywords(MappingMixin):
+
+    def __init__(self, node):
+        self.node = node
+        self.parent = node.parent
+        self._markers = {node.name: True}
+
+    def __getitem__(self, key):
+        try:
+            return self._markers[key]
+        except KeyError:
+            if self.parent is None:
+                raise
+            return self.parent.keywords[key]
+
+    def __setitem__(self, key, value):
+        self._markers[key] = value
+
+    def __delitem__(self, key):
+        raise ValueError("cannot delete key in keywords dict")
+
+    def __iter__(self):
+        seen = self._seen()
+        return iter(seen)
+
+    def _seen(self):
+        seen = set(self._markers)
+        if self.parent is not None:
+            seen.update(self.parent.keywords)
+        return seen
+
+    def __len__(self):
+        return len(self._seen())
+
+    def __repr__(self):
+        return "<NodeKeywords for node %s>" % (self.node,)
+
+
+@attr.s(cmp=False, hash=False)
+class NodeMarkers(object):
+    """
+    internal strucutre for storing marks belongong to a node
+
+    ..warning::
+
+        unstable api
+
+    """
+    own_markers = attr.ib(default=attr.Factory(list))
+
+    def update(self, add_markers):
+        """update the own markers
+        """
+        self.own_markers.extend(add_markers)
+
+    def find(self, name):
+        """
+        find markers in own nodes or parent nodes
+        needs a better place
+        """
+        for mark in self.own_markers:
+            if mark.name == name:
+                yield mark
+
+    def __iter__(self):
+        return iter(self.own_markers)
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/monkeypatch.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/monkeypatch.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/monkeypatch.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/monkeypatch.py
@@ -1,14 +1,16 @@
 """ monkeypatching and mocking functionality.  """
 from __future__ import absolute_import, division, print_function
 
 import os
 import sys
 import re
+from contextlib import contextmanager
+
 import six
 from _pytest.fixtures import fixture
 
 RE_IMPORT_ERROR_NAME = re.compile("^No module named (.*)$")
 
 
 @fixture
 def monkeypatch():
@@ -31,108 +33,129 @@ def monkeypatch():
     """
     mpatch = MonkeyPatch()
     yield mpatch
     mpatch.undo()
 
 
 def resolve(name):
     # simplified from zope.dottedname
-    parts = name.split('.')
+    parts = name.split(".")
 
     used = parts.pop(0)
     found = __import__(used)
     for part in parts:
-        used += '.' + part
+        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)
-                )
+                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
-            )
+            "%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, six.string_types) or "." not in import_path:
-        raise TypeError("must be absolute import path string, not %r" %
-                        (import_path,))
-    module, attr = import_path.rsplit('.', 1)
+        raise TypeError("must be absolute import path string, not %r" % (import_path,))
+    module, attr = import_path.rsplit(".", 1)
     target = resolve(module)
     if raising:
         annotated_getattr(target, attr, ann=module)
     return attr, target
 
 
-class Notset:
+class Notset(object):
+
     def __repr__(self):
         return "<notset>"
 
 
 notset = Notset()
 
 
-class MonkeyPatch:
+class MonkeyPatch(object):
     """ 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
 
+    @contextmanager
+    def context(self):
+        """
+        Context manager that returns a new :class:`MonkeyPatch` object which
+        undoes any patching done inside the ``with`` block upon exit:
+
+        .. code-block:: python
+
+            import functools
+            def test_partial(monkeypatch):
+                with monkeypatch.context() as m:
+                    m.setattr(functools, "partial", 3)
+
+        Useful in situations where it is desired to undo some patches before the test ends,
+        such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples
+        of this see `#3290 <https://github.com/pytest-dev/pytest/issues/3290>`_.
+        """
+        m = MonkeyPatch()
+        try:
+            yield m
+        finally:
+            m.undo()
+
     def setattr(self, target, name, value=notset, raising=True):
         """ Set attribute value on target, memorizing the old value.
         By default raise AttributeError if the attribute did not exist.
 
         For convenience you can specify a string as ``target`` which
         will be interpreted as a dotted import path, with the last part
         being the attribute name.  Example:
-        ``monkeypatch.setattr("os.getcwd", lambda x: "/")``
+        ``monkeypatch.setattr("os.getcwd", lambda: "/")``
         would set the ``getcwd`` function of the ``os`` module.
 
         The ``raising`` value determines if the setattr should fail
         if the attribute is not already present (defaults to True
         which means it will raise).
         """
         __tracebackhide__ = True
         import inspect
 
         if value is notset:
             if not isinstance(target, six.string_types):
-                raise TypeError("use setattr(target, name, value) or "
-                                "setattr(target, value) with target being a dotted "
-                                "import string")
+                raise TypeError(
+                    "use setattr(target, name, value) or "
+                    "setattr(target, value) with target being a dotted "
+                    "import string"
+                )
             value = name
             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))
 
         # avoid class descriptors like staticmethod/classmethod
@@ -150,19 +173,21 @@ class MonkeyPatch:
         last part being the attribute name.
 
         If ``raising`` is set to False, no exception will be raised if the
         attribute is missing.
         """
         __tracebackhide__ = True
         if name is notset:
             if not isinstance(target, six.string_types):
-                raise TypeError("use delattr(target, name) or "
-                                "delattr(target) with target being a dotted "
-                                "import string")
+                raise TypeError(
+                    "use delattr(target, name) or "
+                    "delattr(target) with target being a dotted "
+                    "import string"
+                )
             name, target = derive_importpath(target, raising)
 
         if not hasattr(target, name):
             if raising:
                 raise AttributeError(name)
         else:
             self._setattr.append((target, name, getattr(target, name, notset)))
             delattr(target, name)
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/nodes.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/nodes.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/nodes.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/nodes.py
@@ -1,27 +1,41 @@
+from __future__ import absolute_import, division, print_function
+import os
+
+import six
+import py
+import attr
+
+import _pytest
+import _pytest._code
+
+from _pytest.mark.structures import NodeKeywords, MarkInfo
+
 SEP = "/"
 
+tracebackcutdir = py.path.local(_pytest.__file__).dirpath()
+
 
 def _splitnode(nodeid):
     """Split a nodeid into constituent 'parts'.
 
     Node IDs are strings, and can be things like:
         ''
         'testing/code'
         'testing/code/test_excinfo.py'
         'testing/code/test_excinfo.py::TestFormattedExcinfo::()'
 
     Return values are lists e.g.
         []
         ['testing', 'code']
         ['testing', 'code', 'test_excinfo.py']
         ['testing', 'code', 'test_excinfo.py', 'TestFormattedExcinfo', '()']
     """
-    if nodeid == '':
+    if nodeid == "":
         # If there is no root node at all, return an empty list so the caller's logic can remain sane
         return []
     parts = nodeid.split(SEP)
     # Replace single last element 'test_foo.py::Bar::()' with multiple elements 'test_foo.py', 'Bar', '()'
     parts[-1:] = parts[-1].split("::")
     return parts
 
 
@@ -30,8 +44,376 @@ def ischildnode(baseid, nodeid):
 
     E.g. 'foo/bar::Baz::()' is a child of 'foo', 'foo/bar' and 'foo/bar::Baz', but not of 'foo/blorp'
     """
     base_parts = _splitnode(baseid)
     node_parts = _splitnode(nodeid)
     if len(node_parts) < len(base_parts):
         return False
     return node_parts[:len(base_parts)] == base_parts
+
+
+@attr.s
+class _CompatProperty(object):
+    name = attr.ib()
+
+    def __get__(self, obj, owner):
+        if obj is None:
+            return self
+
+        # TODO: reenable in the features branch
+        # warnings.warn(
+        #     "usage of {owner!r}.{name} is deprecated, please use pytest.{name} instead".format(
+        #         name=self.name, owner=type(owner).__name__),
+        #     PendingDeprecationWarning, stacklevel=2)
+        return getattr(__import__("pytest"), self.name)
+
+
+class Node(object):
+    """ base class for Collector and Item the test collection tree.
+    Collector subclasses have children, Items are terminal nodes."""
+
+    def __init__(
+        self, name, parent=None, config=None, session=None, fspath=None, nodeid=None
+    ):
+        #: a unique name within the scope of the parent node
+        self.name = name
+
+        #: the parent collector node.
+        self.parent = parent
+
+        #: the pytest config object
+        self.config = config or parent.config
+
+        #: the session this node is part of
+        self.session = session or parent.session
+
+        #: filesystem path where this node was collected from (can be None)
+        self.fspath = fspath or getattr(parent, "fspath", None)
+
+        #: keywords/markers collected from all scopes
+        self.keywords = NodeKeywords(self)
+
+        #: the marker objects belonging to this node
+        self.own_markers = []
+
+        #: allow adding of extra keywords to use for matching
+        self.extra_keyword_matches = set()
+
+        # used for storing artificial fixturedefs for direct parametrization
+        self._name2pseudofixturedef = {}
+
+        if nodeid is not None:
+            self._nodeid = nodeid
+        else:
+            assert parent is not None
+            self._nodeid = self.parent.nodeid + "::" + self.name
+
+    @property
+    def ihook(self):
+        """ fspath sensitive hook proxy used to call pytest hooks"""
+        return self.session.gethookproxy(self.fspath)
+
+    Module = _CompatProperty("Module")
+    Class = _CompatProperty("Class")
+    Instance = _CompatProperty("Instance")
+    Function = _CompatProperty("Function")
+    File = _CompatProperty("File")
+    Item = _CompatProperty("Item")
+
+    def _getcustomclass(self, name):
+        maybe_compatprop = getattr(type(self), name)
+        if isinstance(maybe_compatprop, _CompatProperty):
+            return getattr(__import__("pytest"), name)
+        else:
+            cls = getattr(self, name)
+            # TODO: reenable in the features branch
+            # warnings.warn("use of node.%s is deprecated, "
+            #    "use pytest_pycollect_makeitem(...) to create custom "
+            #    "collection nodes" % name, category=DeprecationWarning)
+        return cls
+
+    def __repr__(self):
+        return "<%s %r>" % (self.__class__.__name__, getattr(self, "name", None))
+
+    def warn(self, code, message):
+        """ generate a warning with the given code and message for this
+        item. """
+        assert isinstance(code, str)
+        fslocation = getattr(self, "location", None)
+        if fslocation is None:
+            fslocation = getattr(self, "fspath", None)
+        self.ihook.pytest_logwarning.call_historic(
+            kwargs=dict(
+                code=code, message=message, nodeid=self.nodeid, fslocation=fslocation
+            )
+        )
+
+    # methods for ordering nodes
+    @property
+    def nodeid(self):
+        """ a ::-separated string denoting its collection tree address. """
+        return self._nodeid
+
+    def __hash__(self):
+        return hash(self.nodeid)
+
+    def setup(self):
+        pass
+
+    def teardown(self):
+        pass
+
+    def listchain(self):
+        """ return list of all parent collectors up to self,
+            starting from root of collection tree. """
+        chain = []
+        item = self
+        while item is not None:
+            chain.append(item)
+            item = item.parent
+        chain.reverse()
+        return chain
+
+    def add_marker(self, marker):
+        """dynamically add a marker object to the node.
+
+        :type marker: str or pytest.mark.*
+        """
+        from _pytest.mark import MarkDecorator, MARK_GEN
+
+        if isinstance(marker, six.string_types):
+            marker = getattr(MARK_GEN, marker)
+        elif not isinstance(marker, MarkDecorator):
+            raise ValueError("is not a string or pytest.mark.* Marker")
+        self.keywords[marker.name] = marker
+        self.own_markers.append(marker.mark)
+
+    def iter_markers(self, name=None):
+        """
+        :param name: if given, filter the results by the name attribute
+
+        iterate over all markers of the node
+        """
+        return (x[1] for x in self.iter_markers_with_node(name=name))
+
+    def iter_markers_with_node(self, name=None):
+        """
+        :param name: if given, filter the results by the name attribute
+
+        iterate over all markers of the node
+        returns sequence of tuples (node, mark)
+        """
+        for node in reversed(self.listchain()):
+            for mark in node.own_markers:
+                if name is None or getattr(mark, "name", None) == name:
+                    yield node, mark
+
+    def get_closest_marker(self, name, default=None):
+        """return the first marker matching the name, from closest (for example function) to farther level (for example
+        module level).
+
+        :param default: fallback return value of no marker was found
+        :param name: name to filter by
+        """
+        return next(self.iter_markers(name=name), default)
+
+    def get_marker(self, name):
+        """ get a marker object from this node or None if
+        the node doesn't have a marker with that name.
+
+        .. deprecated:: 3.6
+            This function has been deprecated in favor of
+            :meth:`Node.get_closest_marker <_pytest.nodes.Node.get_closest_marker>` and
+            :meth:`Node.iter_markers <_pytest.nodes.Node.iter_markers>`, see :ref:`update marker code`
+            for more details.
+        """
+        markers = list(self.iter_markers(name=name))
+        if markers:
+            return MarkInfo(markers)
+
+    def listextrakeywords(self):
+        """ Return a set of all extra keywords in self and any parents."""
+        extra_keywords = set()
+        for item in self.listchain():
+            extra_keywords.update(item.extra_keyword_matches)
+        return extra_keywords
+
+    def listnames(self):
+        return [x.name for x in self.listchain()]
+
+    def addfinalizer(self, fin):
+        """ register a function to be called when this node is finalized.
+
+        This method can only be called when this node is active
+        in a setup chain, for example during self.setup().
+        """
+        self.session._setupstate.addfinalizer(fin, self)
+
+    def getparent(self, cls):
+        """ get the next parent node (including ourself)
+        which is an instance of the given class"""
+        current = self
+        while current and not isinstance(current, cls):
+            current = current.parent
+        return current
+
+    def _prunetraceback(self, excinfo):
+        pass
+
+    def _repr_failure_py(self, excinfo, style=None):
+        fm = self.session._fixturemanager
+        if excinfo.errisinstance(fm.FixtureLookupError):
+            return excinfo.value.formatrepr()
+        tbfilter = True
+        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"
+        # XXX should excinfo.getrepr record all data and toterminal() process it?
+        if style is None:
+            if self.config.option.tbstyle == "short":
+                style = "short"
+            else:
+                style = "long"
+
+        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,
+        )
+
+    repr_failure = _repr_failure_py
+
+
+class Collector(Node):
+    """ Collector instances create children through collect()
+        and thus iteratively build a tree.
+    """
+
+    class CollectError(Exception):
+        """ an error during collection, contains a custom message. """
+
+    def collect(self):
+        """ returns a list of children (items and collectors)
+            for this collection node.
+        """
+        raise NotImplementedError("abstract")
+
+    def repr_failure(self, excinfo):
+        """ represent a collection failure. """
+        if excinfo.errisinstance(self.CollectError):
+            exc = excinfo.value
+            return str(exc.args[0])
+        return self._repr_failure_py(excinfo, style="short")
+
+    def _prunetraceback(self, excinfo):
+        if hasattr(self, "fspath"):
+            traceback = excinfo.traceback
+            ntraceback = traceback.cut(path=self.fspath)
+            if ntraceback == traceback:
+                ntraceback = ntraceback.cut(excludepath=tracebackcutdir)
+            excinfo.traceback = ntraceback.filter()
+
+
+def _check_initialpaths_for_relpath(session, fspath):
+    for initial_path in session._initialpaths:
+        if fspath.common(initial_path) == initial_path:
+            return fspath.relto(initial_path.dirname)
+
+
+class FSCollector(Collector):
+
+    def __init__(self, fspath, parent=None, config=None, session=None, nodeid=None):
+        fspath = py.path.local(fspath)  # xxx only for test_resultlog.py?
+        name = fspath.basename
+        if parent is not None:
+            rel = fspath.relto(parent.fspath)
+            if rel:
+                name = rel
+            name = name.replace(os.sep, SEP)
+        self.fspath = fspath
+
+        session = session or parent.session
+
+        if nodeid is None:
+            nodeid = self.fspath.relto(session.config.rootdir)
+
+            if not nodeid:
+                nodeid = _check_initialpaths_for_relpath(session, fspath)
+            if os.sep != SEP:
+                nodeid = nodeid.replace(os.sep, SEP)
+
+        super(FSCollector, self).__init__(
+            name, parent, config, session, nodeid=nodeid, fspath=fspath
+        )
+
+
+class File(FSCollector):
+    """ base class for collecting tests from a file. """
+
+
+class Item(Node):
+    """ a basic test invocation item. Note that for a single function
+    there might be multiple test invocation items.
+    """
+    nextitem = None
+
+    def __init__(self, name, parent=None, config=None, session=None, nodeid=None):
+        super(Item, self).__init__(name, parent, config, session, nodeid=nodeid)
+        self._report_sections = []
+
+        #: user properties is a list of tuples (name, value) that holds user
+        #: defined properties for this test.
+        self.user_properties = []
+
+    def add_report_section(self, when, key, content):
+        """
+        Adds a new report section, similar to what's done internally to add stdout and
+        stderr captured output::
+
+            item.add_report_section("call", "stdout", "report section contents")
+
+        :param str when:
+            One of the possible capture states, ``"setup"``, ``"call"``, ``"teardown"``.
+        :param str key:
+            Name of the section, can be customized at will. Pytest uses ``"stdout"`` and
+            ``"stderr"`` internally.
+
+        :param str content:
+            The full contents as a string.
+        """
+        if content:
+            self._report_sections.append((when, key, content))
+
+    def reportinfo(self):
+        return self.fspath, None, ""
+
+    @property
+    def location(self):
+        try:
+            return self._location
+        except AttributeError:
+            location = self.reportinfo()
+            # bestrelpath is a quite slow function
+            cache = self.config.__dict__.setdefault("_bestrelpathcache", {})
+            try:
+                fspath = cache[location[0]]
+            except KeyError:
+                fspath = self.session.fspath.bestrelpath(location[0])
+                cache[location[0]] = fspath
+            location = (fspath, location[1], str(location[2]))
+            self._location = location
+            return location
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/nose.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/nose.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/nose.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/nose.py
@@ -4,67 +4,67 @@ from __future__ import absolute_import, 
 import sys
 
 from _pytest import unittest, runner, python
 from _pytest.config import hookimpl
 
 
 def get_skip_exceptions():
     skip_classes = set()
-    for module_name in ('unittest', 'unittest2', 'nose'):
+    for module_name in ("unittest", "unittest2", "nose"):
         mod = sys.modules.get(module_name)
-        if hasattr(mod, 'SkipTest'):
+        if hasattr(mod, "SkipTest"):
             skip_classes.add(mod.SkipTest)
     return tuple(skip_classes)
 
 
 def pytest_runtest_makereport(item, call):
     if call.excinfo and call.excinfo.errisinstance(get_skip_exceptions()):
         # let's substitute the excinfo with a pytest.skip one
-        call2 = call.__class__(
-            lambda: runner.skip(str(call.excinfo.value)), call.when)
+        call2 = call.__class__(lambda: runner.skip(str(call.excinfo.value)), call.when)
         call.excinfo = call2.excinfo
 
 
 @hookimpl(trylast=True)
 def pytest_runtest_setup(item):
     if is_potential_nosetest(item):
         if isinstance(item.parent, python.Generator):
             gen = item.parent
-            if not hasattr(gen, '_nosegensetup'):
-                call_optional(gen.obj, 'setup')
+            if not hasattr(gen, "_nosegensetup"):
+                call_optional(gen.obj, "setup")
                 if isinstance(gen.parent, python.Instance):
-                    call_optional(gen.parent.obj, 'setup')
+                    call_optional(gen.parent.obj, "setup")
                 gen._nosegensetup = True
-        if not call_optional(item.obj, 'setup'):
+        if not call_optional(item.obj, "setup"):
             # call module level setup if there is no object level one
-            call_optional(item.parent.obj, 'setup')
+            call_optional(item.parent.obj, "setup")
         # XXX this implies we only call teardown when setup worked
         item.session._setupstate.addfinalizer((lambda: teardown_nose(item)), item)
 
 
 def teardown_nose(item):
     if is_potential_nosetest(item):
-        if not call_optional(item.obj, 'teardown'):
-            call_optional(item.parent.obj, 'teardown')
+        if not call_optional(item.obj, "teardown"):
+            call_optional(item.parent.obj, "teardown")
         # if hasattr(item.parent, '_nosegensetup'):
         #    #call_optional(item._nosegensetup, 'teardown')
         #    del item.parent._nosegensetup
 
 
 def pytest_make_collect_report(collector):
     if isinstance(collector, python.Generator):
-        call_optional(collector.obj, 'setup')
+        call_optional(collector.obj, "setup")
 
 
 def is_potential_nosetest(item):
     # extra check needed since we do not do nose style setup/teardown
     # on direct unittest style classes
-    return isinstance(item, python.Function) and \
-        not isinstance(item, unittest.TestCaseFunction)
+    return isinstance(item, python.Function) and not isinstance(
+        item, unittest.TestCaseFunction
+    )
 
 
 def call_optional(obj, name):
     method = getattr(obj, name, None)
     isfixture = hasattr(method, "_pytestfixturefunction")
     if method is not None and not isfixture and callable(method):
         # If there's any problems allow the exception to raise rather than
         # silently ignoring them
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/outcomes.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/outcomes.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/outcomes.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/outcomes.py
@@ -6,55 +6,59 @@ from __future__ import absolute_import, 
 import py
 import sys
 
 
 class OutcomeException(BaseException):
     """ OutcomeException and its subclass instances indicate and
         contain info about test and collection outcomes.
     """
+
     def __init__(self, msg=None, pytrace=True):
         BaseException.__init__(self, msg)
         self.msg = msg
         self.pytrace = pytrace
 
     def __repr__(self):
         if self.msg:
             val = self.msg
             if isinstance(val, bytes):
-                val = py._builtin._totext(val, errors='replace')
+                val = py._builtin._totext(val, errors="replace")
             return val
         return "<%s instance>" % (self.__class__.__name__,)
+
     __str__ = __repr__
 
 
 TEST_OUTCOME = (OutcomeException, Exception)
 
 
 class Skipped(OutcomeException):
     # XXX hackish: on 3k we fake to live in the builtins
     # in order to have Skipped exception printing shorter/nicer
-    __module__ = 'builtins'
+    __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'
+    __module__ = "builtins"
 
 
 class Exit(KeyboardInterrupt):
     """ raised for immediate program exits (no tracebacks/summaries)"""
+
     def __init__(self, msg="unknown reason"):
         self.msg = msg
         KeyboardInterrupt.__init__(self, msg)
 
+
 # exposed helper methods
 
 
 def exit(msg):
     """ exit testing process as if KeyboardInterrupt was triggered. """
     __tracebackhide__ = True
     raise Exit(msg)
 
@@ -67,28 +71,28 @@ def skip(msg="", **kwargs):
     better to use the pytest.mark.skipif marker to declare a test to be
     skipped under certain conditions like mismatching platforms or
     dependencies.  See the pytest_skipping plugin for details.
 
     :kwarg bool allow_module_level: allows this function to be called at
         module level, skipping the rest of the module. Default to False.
     """
     __tracebackhide__ = True
-    allow_module_level = kwargs.pop('allow_module_level', False)
+    allow_module_level = kwargs.pop("allow_module_level", False)
     if kwargs:
         keys = [k for k in kwargs.keys()]
-        raise TypeError('unexpected keyword arguments: {0}'.format(keys))
+        raise TypeError("unexpected keyword arguments: {}".format(keys))
     raise Skipped(msg=msg, allow_module_level=allow_module_level)
 
 
 skip.Exception = Skipped
 
 
 def fail(msg="", pytrace=True):
-    """ explicitly fail an currently-executing test with the given Message.
+    """ explicitly fail a 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.
     """
     __tracebackhide__ = True
     raise Failed(msg=msg, pytrace=pytrace)
 
 
@@ -109,39 +113,45 @@ xfail.Exception = XFailed
 
 
 def importorskip(modname, minversion=None):
     """ return imported module if it has at least "minversion" as its
     __version__ attribute.  If no minversion is specified the a skip
     is only triggered if the module can not be imported.
     """
     import warnings
+
     __tracebackhide__ = True
-    compile(modname, '', 'eval')  # to catch syntaxerrors
+    compile(modname, "", "eval")  # to catch syntaxerrors
     should_skip = False
 
     with warnings.catch_warnings():
         # make sure to ignore ImportWarnings that might happen because
         # of existing directories with the same name we're trying to
         # import but without a __init__.py file
-        warnings.simplefilter('ignore')
+        warnings.simplefilter("ignore")
         try:
             __import__(modname)
         except ImportError:
             # 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
-    verattr = getattr(mod, '__version__', None)
+    verattr = getattr(mod, "__version__", None)
     if minversion is not None:
         try:
             from pkg_resources import parse_version as pv
         except ImportError:
-            raise Skipped("we have a required version for %r but can not import "
-                          "pkg_resources to parse version strings." % (modname,),
-                          allow_module_level=True)
+            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):
-            raise Skipped("module %r has __version__ %r, required is: %r" % (
-                          modname, verattr, minversion), allow_module_level=True)
+            raise Skipped(
+                "module %r has __version__ %r, required is: %r"
+                % (modname, verattr, minversion),
+                allow_module_level=True,
+            )
     return mod
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/pastebin.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/pastebin.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/pastebin.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/pastebin.py
@@ -4,97 +4,106 @@ from __future__ import absolute_import, 
 import pytest
 import six
 import sys
 import tempfile
 
 
 def pytest_addoption(parser):
     group = parser.getgroup("terminal reporting")
-    group._addoption('--pastebin', metavar="mode",
-                     action='store', dest="pastebin", default=None,
-                     choices=['failed', 'all'],
-                     help="send failed|all info to bpaste.net pastebin service.")
+    group._addoption(
+        "--pastebin",
+        metavar="mode",
+        action="store",
+        dest="pastebin",
+        default=None,
+        choices=["failed", "all"],
+        help="send failed|all info to bpaste.net pastebin service.",
+    )
 
 
 @pytest.hookimpl(trylast=True)
 def pytest_configure(config):
     if config.option.pastebin == "all":
-        tr = config.pluginmanager.getplugin('terminalreporter')
+        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:
             # pastebin file will be utf-8 encoded binary file
-            config._pastebinfile = tempfile.TemporaryFile('w+b')
+            config._pastebinfile = tempfile.TemporaryFile("w+b")
             oldwrite = tr._tw.write
 
             def tee_write(s, **kwargs):
                 oldwrite(s, **kwargs)
                 if isinstance(s, six.text_type):
-                    s = s.encode('utf-8')
+                    s = s.encode("utf-8")
                 config._pastebinfile.write(s)
 
             tr._tw.write = tee_write
 
 
 def pytest_unconfigure(config):
-    if hasattr(config, '_pastebinfile'):
+    if hasattr(config, "_pastebinfile"):
         # get terminal contents and delete file
         config._pastebinfile.seek(0)
         sessionlog = config._pastebinfile.read()
         config._pastebinfile.close()
         del config._pastebinfile
         # undo our patching in the terminal reporter
-        tr = config.pluginmanager.getplugin('terminalreporter')
-        del tr._tw.__dict__['write']
+        tr = config.pluginmanager.getplugin("terminalreporter")
+        del tr._tw.__dict__["write"]
         # write summary
         tr.write_sep("=", "Sending information to Paste Service")
         pastebinurl = create_new_paste(sessionlog)
         tr.write_line("pastebin session-log: %s\n" % pastebinurl)
 
 
 def create_new_paste(contents):
     """
     Creates a new paste using bpaste.net service.
 
     :contents: paste contents as utf-8 encoded bytes
     :returns: url to the pasted contents
     """
     import re
+
     if sys.version_info < (3, 0):
         from urllib import urlopen, urlencode
     else:
         from urllib.request import urlopen
         from urllib.parse import urlencode
 
     params = {
-        'code': contents,
-        'lexer': 'python3' if sys.version_info[0] == 3 else 'python',
-        'expiry': '1week',
+        "code": contents,
+        "lexer": "python3" if sys.version_info[0] == 3 else "python",
+        "expiry": "1week",
     }
-    url = 'https://bpaste.net'
-    response = urlopen(url, data=urlencode(params).encode('ascii')).read()
-    m = re.search(r'href="/raw/(\w+)"', response.decode('utf-8'))
+    url = "https://bpaste.net"
+    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))
+        return "%s/show/%s" % (url, m.group(1))
     else:
-        return 'bad response: ' + response
+        return "bad response: " + response
 
 
 def pytest_terminal_summary(terminalreporter):
     import _pytest.config
+
     if terminalreporter.config.option.pastebin != "failed":
         return
     tr = terminalreporter
-    if 'failed' in tr.stats:
+    if "failed" in tr.stats:
         terminalreporter.write_sep("=", "Sending information to Paste Service")
-        for rep in terminalreporter.stats.get('failed'):
+        for rep in terminalreporter.stats.get("failed"):
             try:
                 msg = rep.longrepr.reprtraceback.reprentries[-1].reprfileloc
             except AttributeError:
                 msg = tr._getfailureheadline(rep)
-            tw = _pytest.config.create_terminal_writer(terminalreporter.config, stringio=True)
+            tw = _pytest.config.create_terminal_writer(
+                terminalreporter.config, stringio=True
+            )
             rep.toterminal(tw)
             s = tw.stringio.getvalue()
             assert len(s)
             pastebinurl = create_new_paste(s)
             tr.write_line("%s --> %s" % (msg, pastebinurl))
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/pytester.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/pytester.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/pytester.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/pytester.py
@@ -1,9 +1,9 @@
-""" (disabled by default) support for testing pytest and pytest plugins. """
+"""(disabled by default) support for testing pytest and pytest plugins."""
 from __future__ import absolute_import, division, print_function
 
 import codecs
 import gc
 import os
 import platform
 import re
 import subprocess
@@ -18,188 +18,220 @@ from weakref import WeakKeyDictionary
 from _pytest.capture import MultiCapture, SysCapture
 from _pytest._code import Source
 import py
 import pytest
 from _pytest.main import Session, EXIT_OK
 from _pytest.assertion.rewrite import AssertionRewritingHook
 
 
-PYTEST_FULLPATH = os.path.abspath(pytest.__file__.rstrip("oc")).replace("$py.class", ".py")
+PYTEST_FULLPATH = os.path.abspath(pytest.__file__.rstrip("oc")).replace(
+    "$py.class", ".py"
+)
+
+
+IGNORE_PAM = [  # filenames added when obtaining details about the current user
+    u"/var/lib/sss/mc/passwd"
+]
 
 
 def pytest_addoption(parser):
-    # group = parser.getgroup("pytester", "pytester (self-tests) options")
-    parser.addoption('--lsof',
-                     action="store_true", dest="lsof", default=False,
-                     help=("run FD checks if lsof is available"))
+    parser.addoption(
+        "--lsof",
+        action="store_true",
+        dest="lsof",
+        default=False,
+        help=("run FD checks if lsof is available"),
+    )
 
-    parser.addoption('--runpytest', default="inprocess", dest="runpytest",
-                     choices=("inprocess", "subprocess", ),
-                     help=("run pytest sub runs in tests using an 'inprocess' "
-                           "or 'subprocess' (python -m main) method"))
+    parser.addoption(
+        "--runpytest",
+        default="inprocess",
+        dest="runpytest",
+        choices=("inprocess", "subprocess"),
+        help=(
+            "run pytest sub runs in tests using an 'inprocess' "
+            "or 'subprocess' (python -m main) method"
+        ),
+    )
 
 
 def pytest_configure(config):
     if config.getvalue("lsof"):
         checker = LsofFdLeakChecker()
         if checker.matching_platform():
             config.pluginmanager.register(checker)
 
 
 class LsofFdLeakChecker(object):
+
     def get_open_files(self):
         out = self._exec_lsof()
         open_files = self._parse_lsof_output(out)
         return open_files
 
     def _exec_lsof(self):
         pid = os.getpid()
         return py.process.cmdexec("lsof -Ffn0 -p %d" % pid)
 
     def _parse_lsof_output(self, out):
+
         def isopen(line):
-            return line.startswith('f') and ("deleted" not in line and
-                                             'mem' not in line and "txt" not in line and 'cwd' not in line)
+            return line.startswith("f") and (
+                "deleted" not in line
+                and "mem" not in line
+                and "txt" not in line
+                and "cwd" not in line
+            )
 
         open_files = []
 
         for line in out.split("\n"):
             if isopen(line):
-                fields = line.split('\0')
+                fields = line.split("\0")
                 fd = fields[0][1:]
                 filename = fields[1][1:]
-                if filename.startswith('/'):
+                if filename in IGNORE_PAM:
+                    continue
+                if filename.startswith("/"):
                     open_files.append((fd, filename))
 
         return open_files
 
     def matching_platform(self):
         try:
             py.process.cmdexec("lsof -v")
         except (py.process.cmdexec.Error, UnicodeDecodeError):
-            # cmdexec may raise UnicodeDecodeError on Windows systems
-            # with locale other than english:
+            # cmdexec may raise UnicodeDecodeError on Windows systems with
+            # locale other than English:
             # https://bitbucket.org/pytest-dev/py/issues/66
             return False
         else:
             return True
 
     @pytest.hookimpl(hookwrapper=True, tryfirst=True)
     def pytest_runtest_protocol(self, item):
         lines1 = self.get_open_files()
         yield
         if hasattr(sys, "pypy_version_info"):
             gc.collect()
         lines2 = self.get_open_files()
 
-        new_fds = set([t[0] for t in lines2]) - set([t[0] for t in lines1])
+        new_fds = {t[0] for t in lines2} - {t[0] for t in lines1}
         leaked_files = [t for t in lines2 if t[0] in new_fds]
         if leaked_files:
             error = []
             error.append("***** %s FD leakage detected" % len(leaked_files))
             error.extend([str(f) for f in leaked_files])
             error.append("*** Before:")
             error.extend([str(f) for f in lines1])
             error.append("*** After:")
             error.extend([str(f) for f in lines2])
             error.append(error[0])
             error.append("*** function %s:%s: %s " % item.location)
             error.append("See issue #2366")
-            item.warn('', "\n".join(error))
+            item.warn("", "\n".join(error))
 
 
 # XXX copied from execnet's conftest.py - needs to be merged
 winpymap = {
-    'python2.7': r'C:\Python27\python.exe',
-    'python3.4': r'C:\Python34\python.exe',
-    'python3.5': r'C:\Python35\python.exe',
-    'python3.6': r'C:\Python36\python.exe',
+    "python2.7": r"C:\Python27\python.exe",
+    "python3.4": r"C:\Python34\python.exe",
+    "python3.5": r"C:\Python35\python.exe",
+    "python3.6": r"C:\Python36\python.exe",
 }
 
 
 def getexecutable(name, cache={}):
     try:
         return cache[name]
     except KeyError:
         executable = py.path.local.sysfind(name)
         if executable:
             import subprocess
-            popen = subprocess.Popen([str(executable), "--version"],
-                                     universal_newlines=True, stderr=subprocess.PIPE)
+
+            popen = subprocess.Popen(
+                [str(executable), "--version"],
+                universal_newlines=True,
+                stderr=subprocess.PIPE,
+            )
             out, err = popen.communicate()
             if name == "jython":
                 if not err or "2.5" not in err:
                     executable = None
                 if "2.5.2" in err:
                     executable = None  # http://bugs.jython.org/issue1790
             elif popen.returncode != 0:
-                # Handle pyenv's 127.
+                # handle pyenv's 127
                 executable = None
         cache[name] = executable
         return executable
 
 
-@pytest.fixture(params=['python2.7', 'python3.4', 'pypy', 'pypy3'])
+@pytest.fixture(params=["python2.7", "python3.4", "pypy", "pypy3"])
 def anypython(request):
     name = request.param
     executable = getexecutable(name)
     if executable is None:
         if sys.platform == "win32":
             executable = winpymap.get(name, None)
             if executable:
                 executable = py.path.local(executable)
                 if executable.check():
                     return executable
         pytest.skip("no suitable %s found" % (name,))
     return executable
 
+
 # used at least by pytest-xdist plugin
 
 
 @pytest.fixture
 def _pytest(request):
-    """ Return a helper which offers a gethookrecorder(hook)
-    method which returns a HookRecorder instance which helps
-    to make assertions about called hooks.
+    """Return a helper which offers a gethookrecorder(hook) method which
+    returns a HookRecorder instance which helps to make assertions about called
+    hooks.
+
     """
     return PytestArg(request)
 
 
-class PytestArg:
+class PytestArg(object):
+
     def __init__(self, request):
         self.request = request
 
     def gethookrecorder(self, hook):
         hookrecorder = HookRecorder(hook._pm)
         self.request.addfinalizer(hookrecorder.finish_recording)
         return hookrecorder
 
 
 def get_public_names(values):
     """Only return names from iterator values without a leading underscore."""
     return [x for x in values if x[0] != "_"]
 
 
-class ParsedCall:
+class ParsedCall(object):
+
     def __init__(self, name, kwargs):
         self.__dict__.update(kwargs)
         self._name = name
 
     def __repr__(self):
         d = self.__dict__.copy()
-        del d['_name']
+        del d["_name"]
         return "<ParsedCall %r(**%r)>" % (self._name, d)
 
 
-class HookRecorder:
+class HookRecorder(object):
     """Record all hooks called in a plugin manager.
 
-    This wraps all the hook calls in the plugin manager, recording
-    each call before propagating the normal calls.
+    This wraps all the hook calls in the plugin manager, recording each call
+    before propagating the normal calls.
 
     """
 
     def __init__(self, pluginmanager):
         self._pluginmanager = pluginmanager
         self.calls = []
 
         def before(hook_name, hook_impls, kwargs):
@@ -251,56 +283,60 @@ class HookRecorder:
 
     def getcall(self, name):
         values = self.getcalls(name)
         assert len(values) == 1, (name, values)
         return values[0]
 
     # functionality for test reports
 
-    def getreports(self,
-                   names="pytest_runtest_logreport pytest_collectreport"):
+    def getreports(self, names="pytest_runtest_logreport pytest_collectreport"):
         return [x.report for x in self.getcalls(names)]
 
-    def matchreport(self, inamepart="",
-                    names="pytest_runtest_logreport pytest_collectreport", when=None):
-        """ return a testreport whose dotted import path matches """
+    def matchreport(
+        self,
+        inamepart="",
+        names="pytest_runtest_logreport pytest_collectreport",
+        when=None,
+    ):
+        """return a testreport whose dotted import path matches"""
         values = []
         for rep in self.getreports(names=names):
             try:
                 if not when and rep.when != "call" and rep.passed:
                     # setup/teardown passing reports - let's ignore those
                     continue
             except AttributeError:
                 pass
-            if when and getattr(rep, 'when', None) != when:
+            if when and getattr(rep, "when", None) != when:
                 continue
             if not inamepart or inamepart in rep.nodeid.split("::"):
                 values.append(rep)
         if not values:
-            raise ValueError("could not find test report matching %r: "
-                             "no test reports at all!" % (inamepart,))
+            raise ValueError(
+                "could not find test report matching %r: "
+                "no test reports at all!" % (inamepart,)
+            )
         if len(values) > 1:
             raise ValueError(
-                "found 2 or more testreports matching %r: %s" % (inamepart, values))
+                "found 2 or more testreports matching %r: %s" % (inamepart, values)
+            )
         return values[0]
 
-    def getfailures(self,
-                    names='pytest_runtest_logreport pytest_collectreport'):
+    def getfailures(self, names="pytest_runtest_logreport pytest_collectreport"):
         return [rep for rep in self.getreports(names) if rep.failed]
 
     def getfailedcollections(self):
-        return self.getfailures('pytest_collectreport')
+        return self.getfailures("pytest_collectreport")
 
     def listoutcomes(self):
         passed = []
         skipped = []
         failed = []
-        for rep in self.getreports(
-                "pytest_collectreport pytest_runtest_logreport"):
+        for rep in self.getreports("pytest_collectreport pytest_runtest_logreport"):
             if rep.passed:
                 if getattr(rep, "when", None) == "call":
                     passed.append(rep)
             elif rep.skipped:
                 skipped.append(rep)
             elif rep.failed:
                 failed.append(rep)
         return passed, skipped, failed
@@ -318,164 +354,193 @@ class HookRecorder:
         self.calls[:] = []
 
 
 @pytest.fixture
 def linecomp(request):
     return LineComp()
 
 
-@pytest.fixture(name='LineMatcher')
+@pytest.fixture(name="LineMatcher")
 def LineMatcher_fixture(request):
     return LineMatcher
 
 
 @pytest.fixture
 def testdir(request, tmpdir_factory):
     return Testdir(request, tmpdir_factory)
 
 
 rex_outcome = re.compile(r"(\d+) ([\w-]+)")
 
 
-class RunResult:
+class RunResult(object):
     """The result of running a command.
 
     Attributes:
 
-    :ret: The return value.
-    :outlines: List of lines captured from stdout.
-    :errlines: List of lines captures from stderr.
+    :ret: the return value
+    :outlines: list of lines captured from stdout
+    :errlines: list of lines captures from stderr
     :stdout: :py:class:`LineMatcher` of stdout, use ``stdout.str()`` to
-       reconstruct stdout or the commonly used
-       ``stdout.fnmatch_lines()`` method.
-    :stderrr: :py:class:`LineMatcher` of stderr.
-    :duration: Duration in seconds.
+       reconstruct stdout or the commonly used ``stdout.fnmatch_lines()``
+       method
+    :stderr: :py:class:`LineMatcher` of stderr
+    :duration: duration in seconds
 
     """
 
     def __init__(self, ret, outlines, errlines, duration):
         self.ret = ret
         self.outlines = outlines
         self.errlines = errlines
         self.stdout = LineMatcher(outlines)
         self.stderr = LineMatcher(errlines)
         self.duration = duration
 
     def parseoutcomes(self):
-        """ Return a dictionary of outcomestring->num from parsing
-        the terminal output that the test process produced."""
+        """Return a dictionary of outcomestring->num from parsing the terminal
+        output that the test process produced.
+
+        """
         for line in reversed(self.outlines):
-            if 'seconds' in line:
+            if "seconds" in line:
                 outcomes = rex_outcome.findall(line)
                 if outcomes:
                     d = {}
                     for num, cat in outcomes:
                         d[cat] = int(num)
                     return d
         raise ValueError("Pytest terminal report not found")
 
     def assert_outcomes(self, passed=0, skipped=0, failed=0, error=0):
-        """ assert that the specified outcomes appear with the respective
-        numbers (0 means it didn't occur) in the text output from a test run."""
+        """Assert that the specified outcomes appear with the respective
+        numbers (0 means it didn't occur) in the text output from a test run.
+
+        """
         d = self.parseoutcomes()
         obtained = {
-            'passed': d.get('passed', 0),
-            'skipped': d.get('skipped', 0),
-            'failed': d.get('failed', 0),
-            'error': d.get('error', 0),
+            "passed": d.get("passed", 0),
+            "skipped": d.get("skipped", 0),
+            "failed": d.get("failed", 0),
+            "error": d.get("error", 0),
         }
-        assert obtained == dict(passed=passed, skipped=skipped, failed=failed, error=error)
+        assert (
+            obtained == dict(passed=passed, skipped=skipped, failed=failed, error=error)
+        )
+
+
+class CwdSnapshot(object):
+
+    def __init__(self):
+        self.__saved = os.getcwd()
+
+    def restore(self):
+        os.chdir(self.__saved)
 
 
-class Testdir:
+class SysModulesSnapshot(object):
+
+    def __init__(self, preserve=None):
+        self.__preserve = preserve
+        self.__saved = dict(sys.modules)
+
+    def restore(self):
+        if self.__preserve:
+            self.__saved.update(
+                (k, m) for k, m in sys.modules.items() if self.__preserve(k)
+            )
+        sys.modules.clear()
+        sys.modules.update(self.__saved)
+
+
+class SysPathsSnapshot(object):
+
+    def __init__(self):
+        self.__saved = list(sys.path), list(sys.meta_path)
+
+    def restore(self):
+        sys.path[:], sys.meta_path[:] = self.__saved
+
+
+class Testdir(object):
     """Temporary test directory with tools to test/run pytest itself.
 
-    This is based on the ``tmpdir`` fixture but provides a number of
-    methods which aid with testing pytest itself.  Unless
-    :py:meth:`chdir` is used all methods will use :py:attr:`tmpdir` as
-    current working directory.
+    This is based on the ``tmpdir`` fixture but provides a number of methods
+    which aid with testing pytest itself.  Unless :py:meth:`chdir` is used all
+    methods will use :py:attr:`tmpdir` as their current working directory.
 
     Attributes:
 
-    :tmpdir: The :py:class:`py.path.local` instance of the temporary
-       directory.
+    :tmpdir: The :py:class:`py.path.local` instance of the temporary directory.
 
     :plugins: A list of plugins to use with :py:meth:`parseconfig` and
-       :py:meth:`runpytest`.  Initially this is an empty list but
-       plugins can be added to the list.  The type of items to add to
-       the list depend on the method which uses them so refer to them
-       for details.
+       :py:meth:`runpytest`.  Initially this is an empty list but plugins can
+       be added to the list.  The type of items to add to the list depends on
+       the method using them so refer to them for details.
 
     """
 
     def __init__(self, request, tmpdir_factory):
         self.request = request
         self._mod_collections = WeakKeyDictionary()
         name = request.function.__name__
         self.tmpdir = tmpdir_factory.mktemp(name, numbered=True)
         self.plugins = []
-        self._savesyspath = (list(sys.path), list(sys.meta_path))
-        self._savemodulekeys = set(sys.modules)
-        self.chdir()  # always chdir
+        self._cwd_snapshot = CwdSnapshot()
+        self._sys_path_snapshot = SysPathsSnapshot()
+        self._sys_modules_snapshot = self.__take_sys_modules_snapshot()
+        self.chdir()
         self.request.addfinalizer(self.finalize)
         method = self.request.config.getoption("--runpytest")
         if method == "inprocess":
             self._runpytest_method = self.runpytest_inprocess
         elif method == "subprocess":
             self._runpytest_method = self.runpytest_subprocess
 
     def __repr__(self):
         return "<Testdir %r>" % (self.tmpdir,)
 
     def finalize(self):
         """Clean up global state artifacts.
 
-        Some methods modify the global interpreter state and this
-        tries to clean this up.  It does not remove the temporary
-        directory however so it can be looked at after the test run
-        has finished.
+        Some methods modify the global interpreter state and this tries to
+        clean this up.  It does not remove the temporary directory however so
+        it can be looked at after the test run has finished.
 
         """
-        sys.path[:], sys.meta_path[:] = self._savesyspath
-        if hasattr(self, '_olddir'):
-            self._olddir.chdir()
-        self.delete_loaded_modules()
-
-    def delete_loaded_modules(self):
-        """Delete modules that have been loaded during a test.
+        self._sys_modules_snapshot.restore()
+        self._sys_path_snapshot.restore()
+        self._cwd_snapshot.restore()
 
-        This allows the interpreter to catch module changes in case
-        the module is re-imported.
-        """
-        for name in set(sys.modules).difference(self._savemodulekeys):
-            # some zope modules used by twisted-related tests keeps internal
-            # state and can't be deleted; we had some trouble in the past
-            # with zope.interface for example
-            if not name.startswith("zope"):
-                del sys.modules[name]
+    def __take_sys_modules_snapshot(self):
+        # some zope modules used by twisted-related tests keep internal state
+        # and can't be deleted; we had some trouble in the past with
+        # `zope.interface` for example
+        def preserve_module(name):
+            return name.startswith("zope")
+
+        return SysModulesSnapshot(preserve=preserve_module)
 
     def make_hook_recorder(self, pluginmanager):
         """Create a new :py:class:`HookRecorder` for a PluginManager."""
         assert not hasattr(pluginmanager, "reprec")
         pluginmanager.reprec = reprec = HookRecorder(pluginmanager)
         self.request.addfinalizer(reprec.finish_recording)
         return reprec
 
     def chdir(self):
         """Cd into the temporary directory.
 
         This is done automatically upon instantiation.
 
         """
-        old = self.tmpdir.chdir()
-        if not hasattr(self, '_olddir'):
-            self._olddir = old
+        self.tmpdir.chdir()
 
-    def _makefile(self, ext, args, kwargs, encoding='utf-8'):
+    def _makefile(self, ext, args, kwargs, encoding="utf-8"):
         items = list(kwargs.items())
 
         def to_text(s):
             return s.decode(encoding) if isinstance(s, bytes) else six.text_type(s)
 
         if args:
             source = u"\n".join(to_text(x) for x in args)
             basename = self.request.function.__name__
@@ -490,64 +555,64 @@ class Testdir:
             p.write(source.strip().encode(encoding), "wb")
             if ret is None:
                 ret = p
         return ret
 
     def makefile(self, ext, *args, **kwargs):
         """Create a new file in the testdir.
 
-        ext: The extension the file should use, including the dot.
-           E.g. ".py".
+        ext: The extension the file should use, including the dot, e.g. `.py`.
 
-        args: All args will be treated as strings and joined using
-           newlines.  The result will be written as contents to the
-           file.  The name of the file will be based on the test
-           function requesting this fixture.
+        args: All args will be treated as strings and joined using newlines.
+           The result will be written as contents to the file.  The name of the
+           file will be based on the test function requesting this fixture.
            E.g. "testdir.makefile('.txt', 'line1', 'line2')"
 
-        kwargs: Each keyword is the name of a file, while the value of
-           it will be written as contents of the file.
+        kwargs: Each keyword is the name of a file, while the value of it will
+           be written as contents of the file.
            E.g. "testdir.makefile('.ini', pytest='[pytest]\naddopts=-rs\n')"
 
         """
         return self._makefile(ext, args, kwargs)
 
     def makeconftest(self, source):
         """Write a contest.py file with 'source' as contents."""
         return self.makepyfile(conftest=source)
 
     def makeini(self, source):
         """Write a tox.ini file with 'source' as contents."""
-        return self.makefile('.ini', tox=source)
+        return self.makefile(".ini", tox=source)
 
     def getinicfg(self, source):
         """Return the pytest section from the tox.ini config file."""
         p = self.makeini(source)
-        return py.iniconfig.IniConfig(p)['pytest']
+        return py.iniconfig.IniConfig(p)["pytest"]
 
     def makepyfile(self, *args, **kwargs):
         """Shortcut for .makefile() with a .py extension."""
-        return self._makefile('.py', args, kwargs)
+        return self._makefile(".py", args, kwargs)
 
     def maketxtfile(self, *args, **kwargs):
         """Shortcut for .makefile() with a .txt extension."""
-        return self._makefile('.txt', args, kwargs)
+        return self._makefile(".txt", args, kwargs)
 
     def syspathinsert(self, path=None):
         """Prepend a directory to sys.path, defaults to :py:attr:`tmpdir`.
 
-        This is undone automatically after the test.
+        This is undone automatically when this object dies at the end of each
+        test.
+
         """
         if path is None:
             path = self.tmpdir
         sys.path.insert(0, str(path))
-        # a call to syspathinsert() usually means that the caller
-        # wants to import some dynamically created files.
-        # with python3 we thus invalidate import caches.
+        # a call to syspathinsert() usually means that the caller wants to
+        # import some dynamically created files, thus with python3 we
+        # invalidate its import caches
         self._possibly_invalidate_import_caches()
 
     def _possibly_invalidate_import_caches(self):
         # invalidate caches if we can (py33 and above)
         try:
             import importlib
         except ImportError:
             pass
@@ -557,382 +622,400 @@ class Testdir:
 
     def mkdir(self, name):
         """Create a new (sub)directory."""
         return self.tmpdir.mkdir(name)
 
     def mkpydir(self, name):
         """Create a new python package.
 
-        This creates a (sub)directory with an empty ``__init__.py``
-        file so that is recognised as a python package.
+        This creates a (sub)directory with an empty ``__init__.py`` file so it
+        gets recognised as a python package.
 
         """
         p = self.mkdir(name)
         p.ensure("__init__.py")
         return p
 
     Session = Session
 
     def getnode(self, config, arg):
         """Return the collection node of a file.
 
         :param config: :py:class:`_pytest.config.Config` instance, see
-           :py:meth:`parseconfig` and :py:meth:`parseconfigure` to
-           create the configuration.
+           :py:meth:`parseconfig` and :py:meth:`parseconfigure` to create the
+           configuration
 
-        :param arg: A :py:class:`py.path.local` instance of the file.
+        :param arg: a :py:class:`py.path.local` instance of the file
 
         """
         session = Session(config)
-        assert '::' not in str(arg)
+        assert "::" not in str(arg)
         p = py.path.local(arg)
         config.hook.pytest_sessionstart(session=session)
         res = session.perform_collect([str(p)], genitems=False)[0]
         config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK)
         return res
 
     def getpathnode(self, path):
         """Return the collection node of a file.
 
-        This is like :py:meth:`getnode` but uses
-        :py:meth:`parseconfigure` to create the (configured) pytest
-        Config instance.
+        This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to
+        create the (configured) pytest Config instance.
 
-        :param path: A :py:class:`py.path.local` instance of the file.
+        :param path: a :py:class:`py.path.local` instance of the file
 
         """
         config = self.parseconfigure(path)
         session = Session(config)
         x = session.fspath.bestrelpath(path)
         config.hook.pytest_sessionstart(session=session)
         res = session.perform_collect([x], genitems=False)[0]
         config.hook.pytest_sessionfinish(session=session, exitstatus=EXIT_OK)
         return res
 
     def genitems(self, colitems):
         """Generate all test items from a collection node.
 
-        This recurses into the collection node and returns a list of
-        all the test items contained within.
+        This recurses into the collection node and returns a list of all the
+        test items contained within.
 
         """
         session = colitems[0].session
         result = []
         for colitem in colitems:
             result.extend(session.genitems(colitem))
         return result
 
     def runitem(self, source):
         """Run the "test_func" Item.
 
-        The calling test instance (the class which contains the test
-        method) must provide a ``.getrunner()`` method which should
-        return a runner which can run the test protocol for a single
-        item, like e.g. :py:func:`_pytest.runner.runtestprotocol`.
+        The calling test instance (class containing the test method) must
+        provide a ``.getrunner()`` method which should return a runner which
+        can run the test protocol for a single item, e.g.
+        :py:func:`_pytest.runner.runtestprotocol`.
 
         """
         # used from runner functional tests
         item = self.getitem(source)
         # the test class where we are called from wants to provide the runner
         testclassinstance = self.request.instance
         runner = testclassinstance.getrunner()
         return runner(item)
 
     def inline_runsource(self, source, *cmdlineargs):
         """Run a test module in process using ``pytest.main()``.
 
         This run writes "source" into a temporary file and runs
-        ``pytest.main()`` on it, returning a :py:class:`HookRecorder`
-        instance for the result.
+        ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance
+        for the result.
 
-        :param source: The source code of the test module.
+        :param source: the source code of the test module
 
-        :param cmdlineargs: Any extra command line arguments to use.
+        :param cmdlineargs: any extra command line arguments to use
 
-        :return: :py:class:`HookRecorder` instance of the result.
+        :return: :py:class:`HookRecorder` instance of the result
 
         """
         p = self.makepyfile(source)
         values = list(cmdlineargs) + [p]
         return self.inline_run(*values)
 
     def inline_genitems(self, *args):
         """Run ``pytest.main(['--collectonly'])`` in-process.
 
-        Returns a tuple of the collected items and a
-        :py:class:`HookRecorder` instance.
-
-        This runs the :py:func:`pytest.main` function to run all of
-        pytest inside the test process itself like
-        :py:meth:`inline_run`.  However the return value is a tuple of
-        the collection items and a :py:class:`HookRecorder` instance.
+        Runs the :py:func:`pytest.main` function to run all of pytest inside
+        the test process itself like :py:meth:`inline_run`, but returns a
+        tuple of the collected items and a :py:class:`HookRecorder` instance.
 
         """
         rec = self.inline_run("--collect-only", *args)
         items = [x.item for x in rec.getcalls("pytest_itemcollected")]
         return items, rec
 
     def inline_run(self, *args, **kwargs):
         """Run ``pytest.main()`` in-process, returning a HookRecorder.
 
-        This runs the :py:func:`pytest.main` function to run all of
-        pytest inside the test process itself.  This means it can
-        return a :py:class:`HookRecorder` instance which gives more
-        detailed results from then run then can be done by matching
-        stdout/stderr from :py:meth:`runpytest`.
+        Runs the :py:func:`pytest.main` function to run all of pytest inside
+        the test process itself.  This means it can return a
+        :py:class:`HookRecorder` instance which gives more detailed results
+        from that run than can be done by matching stdout/stderr from
+        :py:meth:`runpytest`.
 
-        :param args: Any command line arguments to pass to
-           :py:func:`pytest.main`.
+        :param args: command line arguments to pass to :py:func:`pytest.main`
+
+        :param plugin: (keyword-only) extra plugin instances the
+           ``pytest.main()`` instance should use
+
+        :return: a :py:class:`HookRecorder` instance
 
-        :param plugin: (keyword-only) Extra plugin instances the
-           ``pytest.main()`` instance should use.
+        """
+        finalizers = []
+        try:
+            # When running pytest inline any plugins active in the main test
+            # process are already imported.  So this disables the warning which
+            # will trigger to say they can no longer be rewritten, which is
+            # fine as they have already been rewritten.
+            orig_warn = AssertionRewritingHook._warn_already_imported
 
-        :return: A :py:class:`HookRecorder` instance.
-        """
-        # When running py.test inline any plugins active in the main
-        # test process are already imported.  So this disables the
-        # warning which will trigger to say they can no longer be
-        # rewritten, which is fine as they are already rewritten.
-        orig_warn = AssertionRewritingHook._warn_already_imported
+            def revert_warn_already_imported():
+                AssertionRewritingHook._warn_already_imported = orig_warn
+
+            finalizers.append(revert_warn_already_imported)
+            AssertionRewritingHook._warn_already_imported = lambda *a: None
 
-        def revert():
-            AssertionRewritingHook._warn_already_imported = orig_warn
+            # Any sys.module or sys.path changes done while running pytest
+            # inline should be reverted after the test run completes to avoid
+            # clashing with later inline tests run within the same pytest test,
+            # e.g. just because they use matching test module names.
+            finalizers.append(self.__take_sys_modules_snapshot().restore)
+            finalizers.append(SysPathsSnapshot().restore)
 
-        self.request.addfinalizer(revert)
-        AssertionRewritingHook._warn_already_imported = lambda *a: None
+            # Important note:
+            # - our tests should not leave any other references/registrations
+            #   laying around other than possibly loaded test modules
+            #   referenced from sys.modules, as nothing will clean those up
+            #   automatically
 
-        rec = []
+            rec = []
 
-        class Collect:
-            def pytest_configure(x, config):
-                rec.append(self.make_hook_recorder(config.pluginmanager))
+            class Collect(object):
+
+                def pytest_configure(x, config):
+                    rec.append(self.make_hook_recorder(config.pluginmanager))
 
-        plugins = kwargs.get("plugins") or []
-        plugins.append(Collect())
-        ret = pytest.main(list(args), plugins=plugins)
-        self.delete_loaded_modules()
-        if len(rec) == 1:
-            reprec = rec.pop()
-        else:
-            class reprec:
-                pass
-        reprec.ret = ret
+            plugins = kwargs.get("plugins") or []
+            plugins.append(Collect())
+            ret = pytest.main(list(args), plugins=plugins)
+            if len(rec) == 1:
+                reprec = rec.pop()
+            else:
+
+                class reprec(object):
+                    pass
 
-        # typically we reraise keyboard interrupts from the child run
-        # because it's our user requesting interruption of the testing
-        if ret == 2 and not kwargs.get("no_reraise_ctrlc"):
-            calls = reprec.getcalls("pytest_keyboard_interrupt")
-            if calls and calls[-1].excinfo.type == KeyboardInterrupt:
-                raise KeyboardInterrupt()
-        return reprec
+            reprec.ret = ret
+
+            # typically we reraise keyboard interrupts from the child run
+            # because it's our user requesting interruption of the testing
+            if ret == 2 and not kwargs.get("no_reraise_ctrlc"):
+                calls = reprec.getcalls("pytest_keyboard_interrupt")
+                if calls and calls[-1].excinfo.type == KeyboardInterrupt:
+                    raise KeyboardInterrupt()
+            return reprec
+        finally:
+            for finalizer in finalizers:
+                finalizer()
 
     def runpytest_inprocess(self, *args, **kwargs):
-        """ Return result of running pytest in-process, providing a similar
-        interface to what self.runpytest() provides. """
+        """Return result of running pytest in-process, providing a similar
+        interface to what self.runpytest() provides.
+
+        """
         if kwargs.get("syspathinsert"):
             self.syspathinsert()
         now = time.time()
         capture = MultiCapture(Capture=SysCapture)
         capture.start_capturing()
         try:
             try:
                 reprec = self.inline_run(*args, **kwargs)
             except SystemExit as e:
 
-                class reprec:
+                class reprec(object):
                     ret = e.args[0]
 
             except Exception:
                 traceback.print_exc()
 
-                class reprec:
+                class reprec(object):
                     ret = 3
+
         finally:
             out, err = capture.readouterr()
             capture.stop_capturing()
             sys.stdout.write(out)
             sys.stderr.write(err)
 
-        res = RunResult(reprec.ret,
-                        out.split("\n"), err.split("\n"),
-                        time.time() - now)
+        res = RunResult(reprec.ret, out.split("\n"), err.split("\n"), time.time() - now)
         res.reprec = reprec
         return res
 
     def runpytest(self, *args, **kwargs):
-        """ Run pytest inline or in a subprocess, depending on the command line
+        """Run pytest inline or in a subprocess, depending on the command line
         option "--runpytest" and return a :py:class:`RunResult`.
 
         """
         args = self._ensure_basetemp(args)
         return self._runpytest_method(*args, **kwargs)
 
     def _ensure_basetemp(self, args):
         args = [str(x) for x in args]
         for x in args:
-            if str(x).startswith('--basetemp'):
+            if str(x).startswith("--basetemp"):
                 # print("basedtemp exists: %s" %(args,))
                 break
         else:
-            args.append("--basetemp=%s" % self.tmpdir.dirpath('basetemp'))
+            args.append("--basetemp=%s" % self.tmpdir.dirpath("basetemp"))
             # print("added basetemp: %s" %(args,))
         return args
 
     def parseconfig(self, *args):
         """Return a new pytest Config instance from given commandline args.
 
-        This invokes the pytest bootstrapping code in _pytest.config
-        to create a new :py:class:`_pytest.core.PluginManager` and
-        call the pytest_cmdline_parse hook to create new
+        This invokes the pytest bootstrapping code in _pytest.config to create
+        a new :py:class:`_pytest.core.PluginManager` and call the
+        pytest_cmdline_parse hook to create a new
         :py:class:`_pytest.config.Config` instance.
 
-        If :py:attr:`plugins` has been populated they should be plugin
-        modules which will be registered with the PluginManager.
+        If :py:attr:`plugins` has been populated they should be plugin modules
+        to be registered with the PluginManager.
 
         """
         args = self._ensure_basetemp(args)
 
         import _pytest.config
+
         config = _pytest.config._prepareconfig(args, self.plugins)
         # we don't know what the test will do with this half-setup config
         # object and thus we make sure it gets unconfigured properly in any
         # case (otherwise capturing could still be active, for example)
         self.request.addfinalizer(config._ensure_unconfigure)
         return config
 
     def parseconfigure(self, *args):
         """Return a new pytest configured Config instance.
 
-        This returns a new :py:class:`_pytest.config.Config` instance
-        like :py:meth:`parseconfig`, but also calls the
-        pytest_configure hook.
+        This returns a new :py:class:`_pytest.config.Config` instance like
+        :py:meth:`parseconfig`, but also calls the pytest_configure hook.
 
         """
         config = self.parseconfig(*args)
         config._do_configure()
         self.request.addfinalizer(config._ensure_unconfigure)
         return config
 
     def getitem(self, source, funcname="test_func"):
         """Return the test item for a test function.
 
-        This writes the source to a python file and runs pytest's
-        collection on the resulting module, returning the test item
-        for the requested function name.
+        This writes the source to a python file and runs pytest's collection on
+        the resulting module, returning the test item for the requested
+        function name.
 
-        :param source: The module source.
+        :param source: the module source
 
-        :param funcname: The name of the test function for which the
-           Item must be returned.
+        :param funcname: the name of the test function for which to return a
+            test item
 
         """
         items = self.getitems(source)
         for item in items:
             if item.name == funcname:
                 return item
-        assert 0, "%r item not found in module:\n%s\nitems: %s" % (
-                  funcname, source, items)
+        assert 0, (
+            "%r item not found in module:\n%s\nitems: %s" % (funcname, source, items)
+        )
 
     def getitems(self, source):
         """Return all test items collected from the module.
 
-        This writes the source to a python file and runs pytest's
-        collection on the resulting module, returning all test items
-        contained within.
+        This writes the source to a python file and runs pytest's collection on
+        the resulting module, returning all test items contained within.
 
         """
         modcol = self.getmodulecol(source)
         return self.genitems([modcol])
 
     def getmodulecol(self, source, configargs=(), withinit=False):
         """Return the module collection node for ``source``.
 
-        This writes ``source`` to a file using :py:meth:`makepyfile`
-        and then runs the pytest collection on it, returning the
-        collection node for the test module.
+        This writes ``source`` to a file using :py:meth:`makepyfile` and then
+        runs the pytest collection on it, returning the collection node for the
+        test module.
 
-        :param source: The source code of the module to collect.
+        :param source: the source code of the module to collect
 
-        :param configargs: Any extra arguments to pass to
-           :py:meth:`parseconfigure`.
+        :param configargs: any extra arguments to pass to
+            :py:meth:`parseconfigure`
 
-        :param withinit: Whether to also write a ``__init__.py`` file
-           to the temporary directory to ensure it is a package.
+        :param withinit: whether to also write an ``__init__.py`` file to the
+            same directory to ensure it is a package
 
         """
         kw = {self.request.function.__name__: Source(source).strip()}
         path = self.makepyfile(**kw)
         if withinit:
             self.makepyfile(__init__="#")
         self.config = config = self.parseconfigure(path, *configargs)
         node = self.getnode(config, path)
 
         return node
 
     def collect_by_name(self, modcol, name):
         """Return the collection node for name from the module collection.
 
-        This will search a module collection node for a collection
-        node matching the given name.
+        This will search a module collection node for a collection node
+        matching the given name.
 
-        :param modcol: A module collection node, see
-           :py:meth:`getmodulecol`.
+        :param modcol: a module collection node; see :py:meth:`getmodulecol`
 
-        :param name: The name of the node to return.
+        :param name: the name of the node to return
 
         """
         if modcol not in self._mod_collections:
             self._mod_collections[modcol] = list(modcol.collect())
         for colitem in self._mod_collections[modcol]:
             if colitem.name == name:
                 return colitem
 
     def popen(self, cmdargs, stdout, stderr, **kw):
         """Invoke subprocess.Popen.
 
-        This calls subprocess.Popen making sure the current working
-        directory is the PYTHONPATH.
+        This calls subprocess.Popen making sure the current working directory
+        is in the PYTHONPATH.
 
         You probably want to use :py:meth:`run` instead.
 
         """
         env = os.environ.copy()
-        env['PYTHONPATH'] = os.pathsep.join(filter(None, [
-            str(os.getcwd()), env.get('PYTHONPATH', '')]))
-        kw['env'] = env
+        env["PYTHONPATH"] = os.pathsep.join(
+            filter(None, [str(os.getcwd()), env.get("PYTHONPATH", "")])
+        )
+        kw["env"] = env
 
-        popen = subprocess.Popen(cmdargs, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, **kw)
+        popen = subprocess.Popen(
+            cmdargs, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, **kw
+        )
         popen.stdin.close()
 
         return popen
 
     def run(self, *cmdargs):
         """Run a command with arguments.
 
-        Run a process using subprocess.Popen saving the stdout and
-        stderr.
+        Run a process using subprocess.Popen saving the stdout and stderr.
 
         Returns a :py:class:`RunResult`.
 
         """
         return self._run(*cmdargs)
 
     def _run(self, *cmdargs):
         cmdargs = [str(x) for x in cmdargs]
         p1 = self.tmpdir.join("stdout")
         p2 = self.tmpdir.join("stderr")
-        print("running:", ' '.join(cmdargs))
+        print("running:", " ".join(cmdargs))
         print("     in:", str(py.path.local()))
         f1 = codecs.open(str(p1), "w", encoding="utf8")
         f2 = codecs.open(str(p2), "w", encoding="utf8")
         try:
             now = time.time()
-            popen = self.popen(cmdargs, stdout=f1, stderr=f2,
-                               close_fds=(sys.platform != "win32"))
+            popen = self.popen(
+                cmdargs, stdout=f1, stderr=f2, close_fds=(sys.platform != "win32")
+            )
             ret = popen.wait()
         finally:
             f1.close()
             f2.close()
         f1 = codecs.open(str(p1), "r", encoding="utf8")
         f2 = codecs.open(str(p2), "r", encoding="utf8")
         try:
             out = f1.read().splitlines()
@@ -947,122 +1030,122 @@ class Testdir:
     def _dump_lines(self, lines, fp):
         try:
             for line in lines:
                 print(line, file=fp)
         except UnicodeEncodeError:
             print("couldn't print to %s because of encoding" % (fp,))
 
     def _getpytestargs(self):
-        # we cannot use "(sys.executable,script)"
-        # because on windows the script is e.g. a pytest.exe
-        return (sys.executable, PYTEST_FULLPATH) # noqa
+        # we cannot use `(sys.executable, script)` because on Windows the
+        # script is e.g. `pytest.exe`
+        return (sys.executable, PYTEST_FULLPATH)  # noqa
 
     def runpython(self, script):
         """Run a python script using sys.executable as interpreter.
 
         Returns a :py:class:`RunResult`.
+
         """
         return self.run(sys.executable, script)
 
     def runpython_c(self, command):
         """Run python -c "command", return a :py:class:`RunResult`."""
         return self.run(sys.executable, "-c", command)
 
     def runpytest_subprocess(self, *args, **kwargs):
         """Run pytest as a subprocess with given arguments.
 
-        Any plugins added to the :py:attr:`plugins` list will added
-        using the ``-p`` command line option.  Addtionally
-        ``--basetemp`` is used put any temporary files and directories
-        in a numbered directory prefixed with "runpytest-" so they do
-        not conflict with the normal numberd pytest location for
-        temporary files and directories.
+        Any plugins added to the :py:attr:`plugins` list will added using the
+        ``-p`` command line option.  Additionally ``--basetemp`` is used put
+        any temporary files and directories in a numbered directory prefixed
+        with "runpytest-" so they do not conflict with the normal numbered
+        pytest location for temporary files and directories.
 
         Returns a :py:class:`RunResult`.
 
         """
-        p = py.path.local.make_numbered_dir(prefix="runpytest-",
-                                            keep=None, rootdir=self.tmpdir)
-        args = ('--basetemp=%s' % p, ) + args
-        # for x in args:
-        #    if '--confcutdir' in str(x):
-        #        break
-        # else:
-        #    pass
-        #    args = ('--confcutdir=.',) + args
+        p = py.path.local.make_numbered_dir(
+            prefix="runpytest-", keep=None, rootdir=self.tmpdir
+        )
+        args = ("--basetemp=%s" % p,) + args
         plugins = [x for x in self.plugins if isinstance(x, str)]
         if plugins:
-            args = ('-p', plugins[0]) + args
+            args = ("-p", plugins[0]) + args
         args = self._getpytestargs() + args
         return self.run(*args)
 
     def spawn_pytest(self, string, expect_timeout=10.0):
         """Run pytest using pexpect.
 
-        This makes sure to use the right pytest and sets up the
-        temporary directory locations.
+        This makes sure to use the right pytest and sets up the temporary
+        directory locations.
 
         The pexpect child is returned.
 
         """
         basetemp = self.tmpdir.mkdir("temp-pexpect")
         invoke = " ".join(map(str, self._getpytestargs()))
         cmd = "%s --basetemp=%s %s" % (invoke, basetemp, string)
         return self.spawn(cmd, expect_timeout=expect_timeout)
 
     def spawn(self, cmd, expect_timeout=10.0):
         """Run a command using pexpect.
 
         The pexpect child is returned.
+
         """
         pexpect = pytest.importorskip("pexpect", "3.0")
-        if hasattr(sys, 'pypy_version_info') and '64' in platform.machine():
+        if hasattr(sys, "pypy_version_info") and "64" in platform.machine():
             pytest.skip("pypy-64 bit not supported")
         if sys.platform.startswith("freebsd"):
             pytest.xfail("pexpect does not work reliably on freebsd")
         logfile = self.tmpdir.join("spawn.out").open("wb")
         child = pexpect.spawn(cmd, logfile=logfile)
         self.request.addfinalizer(logfile.close)
         child.timeout = expect_timeout
         return child
 
 
 def getdecoded(out):
     try:
         return out.decode("utf-8")
     except UnicodeDecodeError:
         return "INTERNAL not-utf8-decodeable, truncated string:\n%s" % (
-            py.io.saferepr(out),)
+            py.io.saferepr(out),
+        )
 
 
-class LineComp:
+class LineComp(object):
+
     def __init__(self):
         self.stringio = py.io.TextIO()
 
     def assert_contains_lines(self, lines2):
-        """ assert that lines2 are contained (linearly) in lines1.
-            return a list of extralines found.
+        """Assert that lines2 are contained (linearly) in lines1.
+
+        Return a list of extralines found.
+
         """
         __tracebackhide__ = True
         val = self.stringio.getvalue()
         self.stringio.truncate(0)
         self.stringio.seek(0)
         lines1 = val.split("\n")
         return LineMatcher(lines1).fnmatch_lines(lines2)
 
 
-class LineMatcher:
+class LineMatcher(object):
     """Flexible matching of text.
 
     This is a convenience class to test large texts like the output of
     commands.
 
-    The constructor takes a list of lines without their trailing
-    newlines, i.e. ``text.splitlines()``.
+    The constructor takes a list of lines without their trailing newlines, i.e.
+    ``text.splitlines()``.
 
     """
 
     def __init__(self, lines):
         self.lines = lines
         self._log_output = []
 
     def str(self):
@@ -1072,98 +1155,100 @@ class LineMatcher:
     def _getlines(self, lines2):
         if isinstance(lines2, str):
             lines2 = Source(lines2)
         if isinstance(lines2, Source):
             lines2 = lines2.strip().lines
         return lines2
 
     def fnmatch_lines_random(self, lines2):
-        """Check lines exist in the output using ``fnmatch.fnmatch``, in any order.
+        """Check lines exist in the output using in any order.
 
-        The argument is a list of lines which have to occur in the
-        output, in any order.
+        Lines are checked using ``fnmatch.fnmatch``. The argument is a list of
+        lines which have to occur in the output, in any order.
+
         """
         self._match_lines_random(lines2, fnmatch)
 
     def re_match_lines_random(self, lines2):
         """Check lines exist in the output using ``re.match``, in any order.
 
-        The argument is a list of lines which have to occur in the
-        output, in any order.
+        The argument is a list of lines which have to occur in the output, in
+        any order.
 
         """
         self._match_lines_random(lines2, lambda name, pat: re.match(pat, name))
 
     def _match_lines_random(self, lines2, match_func):
         """Check lines exist in the output.
 
-        The argument is a list of lines which have to occur in the
-        output, in any order.  Each line can contain glob whildcards.
+        The argument is a list of lines which have to occur in the output, in
+        any order.  Each line can contain glob whildcards.
 
         """
         lines2 = self._getlines(lines2)
         for line in lines2:
             for x in self.lines:
                 if line == x or match_func(x, line):
                     self._log("matched: ", repr(line))
                     break
             else:
                 self._log("line %r not found in output" % line)
                 raise ValueError(self._log_text)
 
     def get_lines_after(self, fnline):
         """Return all lines following the given line in the text.
 
         The given line can contain glob wildcards.
+
         """
         for i, line in enumerate(self.lines):
             if fnline == line or fnmatch(line, fnline):
                 return self.lines[i + 1:]
         raise ValueError("line %r not found in output" % fnline)
 
     def _log(self, *args):
-        self._log_output.append(' '.join((str(x) for x in args)))
+        self._log_output.append(" ".join((str(x) for x in args)))
 
     @property
     def _log_text(self):
-        return '\n'.join(self._log_output)
+        return "\n".join(self._log_output)
 
     def fnmatch_lines(self, lines2):
         """Search captured text for matching lines using ``fnmatch.fnmatch``.
 
-        The argument is a list of lines which have to match and can
-        use glob wildcards.  If they do not match a pytest.fail() is
-        called.  The matches and non-matches are also printed on
-        stdout.
+        The argument is a list of lines which have to match and can use glob
+        wildcards.  If they do not match a pytest.fail() is called.  The
+        matches and non-matches are also printed on stdout.
 
         """
-        self._match_lines(lines2, fnmatch, 'fnmatch')
+        self._match_lines(lines2, fnmatch, "fnmatch")
 
     def re_match_lines(self, lines2):
         """Search captured text for matching lines using ``re.match``.
 
         The argument is a list of lines which have to match using ``re.match``.
         If they do not match a pytest.fail() is called.
 
-        The matches and non-matches are also printed on
-        stdout.
+        The matches and non-matches are also printed on stdout.
+
         """
-        self._match_lines(lines2, lambda name, pat: re.match(pat, name), 're.match')
+        self._match_lines(lines2, lambda name, pat: re.match(pat, name), "re.match")
 
     def _match_lines(self, lines2, match_func, match_nickname):
         """Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``.
 
-        :param list[str] lines2: list of string patterns to match. The actual format depends on
-            ``match_func``.
-        :param match_func: a callable ``match_func(line, pattern)`` where line is the captured
-            line from stdout/stderr and pattern is the matching pattern.
+        :param list[str] lines2: list of string patterns to match. The actual
+            format depends on ``match_func``
+        :param match_func: a callable ``match_func(line, pattern)`` where line
+            is the captured line from stdout/stderr and pattern is the matching
+            pattern
+        :param str match_nickname: the nickname for the match function that
+            will be logged to stdout when a match occurs
 
-        :param str match_nickname: the nickname for the match function that will be logged
-            to stdout when a match occurs.
         """
         lines2 = self._getlines(lines2)
         lines1 = self.lines[:]
         nextline = None
         extralines = []
         __tracebackhide__ = True
         for line in lines2:
             nomatchprinted = False
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/python.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/python.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/python.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/python.py
@@ -14,129 +14,175 @@ from itertools import count
 import py
 import six
 from _pytest.mark import MarkerError
 from _pytest.config import hookimpl
 
 import _pytest
 import pluggy
 from _pytest import fixtures
-from _pytest import main
+from _pytest import nodes
 from _pytest import deprecated
 from _pytest.compat import (
-    isclass, isfunction, is_generator, ascii_escaped,
-    REGEX_TYPE, STRING_TYPES, NoneType, NOTSET,
-    get_real_func, getfslineno, safe_getattr,
-    safe_str, getlocation, enum,
+    isclass,
+    isfunction,
+    is_generator,
+    ascii_escaped,
+    REGEX_TYPE,
+    STRING_TYPES,
+    NoneType,
+    NOTSET,
+    get_real_func,
+    getfslineno,
+    safe_getattr,
+    safe_str,
+    getlocation,
+    enum,
+    get_default_arg_names,
 )
 from _pytest.outcomes import fail
-from _pytest.mark import transfer_markers
+from _pytest.mark.structures import transfer_markers, get_unpacked_marks
+
 
-cutdir1 = py.path.local(pluggy.__file__.rstrip("oc"))
-cutdir2 = py.path.local(_pytest.__file__).dirpath()
-cutdir3 = py.path.local(py.__file__).dirpath()
+# relative paths that we use to filter traceback entries from appearing to the user;
+# see filter_traceback
+# note: if we need to add more paths than what we have now we should probably use a list
+# for better maintenance
+_pluggy_dir = py.path.local(pluggy.__file__.rstrip("oc"))
+# pluggy is either a package or a single module depending on the version
+if _pluggy_dir.basename == "__init__.py":
+    _pluggy_dir = _pluggy_dir.dirpath()
+_pytest_dir = py.path.local(_pytest.__file__).dirpath()
+_py_dir = py.path.local(py.__file__).dirpath()
 
 
 def filter_traceback(entry):
     """Return True if a TracebackEntry instance should be removed from tracebacks:
     * dynamically generated code (no code to show up for it);
     * internal traceback from pytest or its internal libraries, py and pluggy.
     """
     # entry.path might sometimes return a str object when the entry
     # points to dynamically generated code
     # see https://bitbucket.org/pytest-dev/py/issues/71
     raw_filename = entry.frame.code.raw.co_filename
-    is_generated = '<' in raw_filename and '>' in raw_filename
+    is_generated = "<" in raw_filename and ">" in raw_filename
     if is_generated:
         return False
-    # entry.path might point to an inexisting file, in which case it will
-    # alsso return a str object. see #1133
+    # entry.path might point to a non-existing file, in which case it will
+    # also return a str object. see #1133
     p = py.path.local(entry.path)
-    return p != cutdir1 and not p.relto(cutdir2) and not p.relto(cutdir3)
+    return not p.relto(_pluggy_dir) and not p.relto(_pytest_dir) and not p.relto(
+        _py_dir
+    )
 
 
 def pyobj_property(name):
+
     def get(self):
-        node = self.getparent(getattr(__import__('pytest'), name))
+        node = self.getparent(getattr(__import__("pytest"), name))
         if node is not None:
             return node.obj
+
     doc = "python %s object this node was collected from (can be None)." % (
-          name.lower(),)
+        name.lower(),
+    )
     return property(get, None, None, doc)
 
 
 def pytest_addoption(parser):
     group = parser.getgroup("general")
-    group.addoption('--fixtures', '--funcargs',
-                    action="store_true", dest="showfixtures", default=False,
-                    help="show available fixtures, sorted by plugin appearance")
     group.addoption(
-        '--fixtures-per-test',
+        "--fixtures",
+        "--funcargs",
+        action="store_true",
+        dest="showfixtures",
+        default=False,
+        help="show available fixtures, sorted by plugin appearance "
+        "(fixtures with leading '_' are only shown with '-v')",
+    )
+    group.addoption(
+        "--fixtures-per-test",
         action="store_true",
         dest="show_fixtures_per_test",
         default=False,
         help="show fixtures per test",
     )
-    parser.addini("usefixtures", type="args", default=[],
-                  help="list of default fixtures to be used with this project")
-    parser.addini("python_files", type="args",
-                  default=['test_*.py', '*_test.py'],
-                  help="glob-style file patterns for Python test module discovery")
-    parser.addini("python_classes", type="args", default=["Test", ],
-                  help="prefixes or glob names for Python test class discovery")
-    parser.addini("python_functions", type="args", default=["test", ],
-                  help="prefixes or glob names for Python test function and "
-                  "method discovery")
+    parser.addini(
+        "usefixtures",
+        type="args",
+        default=[],
+        help="list of default fixtures to be used with this project",
+    )
+    parser.addini(
+        "python_files",
+        type="args",
+        default=["test_*.py", "*_test.py"],
+        help="glob-style file patterns for Python test module discovery",
+    )
+    parser.addini(
+        "python_classes",
+        type="args",
+        default=["Test"],
+        help="prefixes or glob names for Python test class discovery",
+    )
+    parser.addini(
+        "python_functions",
+        type="args",
+        default=["test"],
+        help="prefixes or glob names for Python test function and " "method discovery",
+    )
 
-    group.addoption("--import-mode", default="prepend",
-                    choices=["prepend", "append"], dest="importmode",
-                    help="prepend/append to sys.path when importing test modules, "
-                    "default is to prepend.")
+    group.addoption(
+        "--import-mode",
+        default="prepend",
+        choices=["prepend", "append"],
+        dest="importmode",
+        help="prepend/append to sys.path when importing test modules, "
+        "default is to prepend.",
+    )
 
 
 def pytest_cmdline_main(config):
     if config.option.showfixtures:
         showfixtures(config)
         return 0
     if config.option.show_fixtures_per_test:
         show_fixtures_per_test(config)
         return 0
 
 
 def pytest_generate_tests(metafunc):
     # those alternative spellings are common - raise a specific error to alert
     # the user
-    alt_spellings = ['parameterize', 'parametrise', 'parameterise']
+    alt_spellings = ["parameterize", "parametrise", "parameterise"]
     for attr in alt_spellings:
         if hasattr(metafunc.function, attr):
             msg = "{0} has '{1}', spelling should be 'parametrize'"
             raise MarkerError(msg.format(metafunc.function.__name__, attr))
-    try:
-        markers = metafunc.function.parametrize
-    except AttributeError:
-        return
-    for marker in markers:
+    for marker in metafunc.definition.iter_markers(name="parametrize"):
         metafunc.parametrize(*marker.args, **marker.kwargs)
 
 
 def pytest_configure(config):
-    config.addinivalue_line("markers",
-                            "parametrize(argnames, argvalues): call a test function multiple "
-                            "times passing in different arguments in turn. argvalues generally "
-                            "needs to be a list of values if argnames specifies only one name "
-                            "or a list of tuples of values if argnames specifies multiple names. "
-                            "Example: @parametrize('arg1', [1,2]) would lead to two calls of the "
-                            "decorated test function, one with arg1=1 and another with arg1=2."
-                            "see http://pytest.org/latest/parametrize.html for more info and "
-                            "examples."
-                            )
-    config.addinivalue_line("markers",
-                            "usefixtures(fixturename1, fixturename2, ...): mark tests as needing "
-                            "all of the specified fixtures. see http://pytest.org/latest/fixture.html#usefixtures "
-                            )
+    config.addinivalue_line(
+        "markers",
+        "parametrize(argnames, argvalues): call a test function multiple "
+        "times passing in different arguments in turn. argvalues generally "
+        "needs to be a list of values if argnames specifies only one name "
+        "or a list of tuples of values if argnames specifies multiple names. "
+        "Example: @parametrize('arg1', [1,2]) would lead to two calls of the "
+        "decorated test function, one with arg1=1 and another with arg1=2."
+        "see http://pytest.org/latest/parametrize.html for more info and "
+        "examples.",
+    )
+    config.addinivalue_line(
+        "markers",
+        "usefixtures(fixturename1, fixturename2, ...): mark tests as needing "
+        "all of the specified fixtures. see http://pytest.org/latest/fixture.html#usefixtures ",
+    )
 
 
 @hookimpl(trylast=True)
 def pytest_pyfunc_call(pyfuncitem):
     testfunction = pyfuncitem.obj
     if pyfuncitem._isyieldedfunction():
         testfunction(*pyfuncitem._args)
     else:
@@ -147,17 +193,17 @@ def pytest_pyfunc_call(pyfuncitem):
         testfunction(**testargs)
     return True
 
 
 def pytest_collect_file(path, parent):
     ext = path.ext
     if ext == ".py":
         if not parent.session.isinitpath(path):
-            for pat in parent.config.getini('python_files'):
+            for pat in parent.config.getini("python_files"):
                 if path.fnmatch(pat):
                     break
             else:
                 return
         ihook = parent.session.gethookproxy(path)
         return ihook.pytest_pycollect_makemodule(path=path, parent=parent)
 
 
@@ -178,18 +224,20 @@ def pytest_pycollect_makeitem(collector,
             outcome.force_result(Class(name, parent=collector))
     elif collector.istestfunction(obj, name):
         # mock seems to store unbound methods (issue473), normalize it
         obj = getattr(obj, "__func__", obj)
         # We need to try and unwrap the function if it's a functools.partial
         # or a funtools.wrapped.
         # We musn't if it's been wrapped with mock.patch (python 2 only)
         if not (isfunction(obj) or isfunction(get_real_func(obj))):
-            collector.warn(code="C2", message="cannot collect %r because it is not a function."
-                           % name, )
+            collector.warn(
+                code="C2",
+                message="cannot collect %r because it is not a function." % name,
+            )
         elif getattr(obj, "__test__", True):
             if is_generator(obj):
                 res = Generator(name, parent=collector)
             else:
                 res = list(collector._genfunctions(name, obj))
             outcome.force_result(res)
 
 
@@ -199,21 +247,31 @@ def pytest_make_parametrize_id(config, v
 
 class PyobjContext(object):
     module = pyobj_property("Module")
     cls = pyobj_property("Class")
     instance = pyobj_property("Instance")
 
 
 class PyobjMixin(PyobjContext):
+    _ALLOW_MARKERS = True
+
+    def __init__(self, *k, **kw):
+        super(PyobjMixin, self).__init__(*k, **kw)
+
     def obj():
+
         def fget(self):
-            obj = getattr(self, '_obj', None)
+            obj = getattr(self, "_obj", None)
             if obj is None:
                 self._obj = obj = self._getobj()
+                # XXX evil hack
+                # used to avoid Instance collector marker duplication
+                if self._ALLOW_MARKERS:
+                    self.own_markers.extend(get_unpacked_marks(self.obj))
             return obj
 
         def fset(self, value):
             self._obj = value
 
         return property(fget, fset, None, "underlying python object")
 
     obj = obj()
@@ -242,61 +300,60 @@ class PyobjMixin(PyobjContext):
         return s.replace(".[", "[")
 
     def _getfslineno(self):
         return getfslineno(self.obj)
 
     def reportinfo(self):
         # XXX caching?
         obj = self.obj
-        compat_co_firstlineno = getattr(obj, 'compat_co_firstlineno', None)
+        compat_co_firstlineno = getattr(obj, "compat_co_firstlineno", None)
         if isinstance(compat_co_firstlineno, int):
             # nose compatibility
             fspath = sys.modules[obj.__module__].__file__
             if fspath.endswith(".pyc"):
                 fspath = fspath[:-1]
             lineno = compat_co_firstlineno
         else:
             fspath, lineno = getfslineno(obj)
         modpath = self.getmodpath()
         assert isinstance(lineno, int)
         return fspath, lineno, modpath
 
 
-class PyCollector(PyobjMixin, main.Collector):
+class PyCollector(PyobjMixin, nodes.Collector):
 
     def funcnamefilter(self, name):
-        return self._matches_prefix_or_glob_option('python_functions', name)
+        return self._matches_prefix_or_glob_option("python_functions", name)
 
     def isnosetest(self, obj):
         """ Look for the __test__ attribute, which is applied by the
         @nose.tools.istest decorator
         """
         # We explicitly check for "is True" here to not mistakenly treat
         # classes with a custom __getattr__ returning something truthy (like a
         # function) as test classes.
-        return safe_getattr(obj, '__test__', False) is True
+        return safe_getattr(obj, "__test__", False) is True
 
     def classnamefilter(self, name):
-        return self._matches_prefix_or_glob_option('python_classes', name)
+        return self._matches_prefix_or_glob_option("python_classes", name)
 
     def istestfunction(self, obj, name):
         if self.funcnamefilter(name) or self.isnosetest(obj):
             if isinstance(obj, staticmethod):
                 # static methods need to be unwrapped
-                obj = safe_getattr(obj, '__func__', False)
+                obj = safe_getattr(obj, "__func__", False)
                 if obj is False:
                     # Python 2.6 wraps in a different way that we won't try to handle
-                    msg = "cannot collect static method %r because " \
-                          "it is not a function (always the case in Python 2.6)"
-                    self.warn(
-                        code="C2", message=msg % name)
+                    msg = "cannot collect static method %r because it is not a function"
+                    self.warn(code="C2", message=msg % name)
                     return False
             return (
-                safe_getattr(obj, "__call__", False) and fixtures.getfixturemarker(obj) is None
+                safe_getattr(obj, "__call__", False)
+                and fixtures.getfixturemarker(obj) is None
             )
         else:
             return False
 
     def istestclass(self, obj, name):
         return self.classnamefilter(name) or self.isnosetest(obj)
 
     def _matches_prefix_or_glob_option(self, option_name, name):
@@ -305,28 +362,29 @@ class PyCollector(PyobjMixin, main.Colle
         in ini configuration.
         """
         for option in self.config.getini(option_name):
             if name.startswith(option):
                 return True
             # check that name looks like a glob-string before calling fnmatch
             # because this is called for every name in each collected module,
             # and fnmatch is somewhat expensive to call
-            elif ('*' in option or '?' in option or '[' in option) and \
-                    fnmatch.fnmatch(name, option):
+            elif ("*" in option or "?" in option or "[" in option) and fnmatch.fnmatch(
+                name, option
+            ):
                 return True
         return False
 
     def collect(self):
         if not getattr(self.obj, "__test__", True):
             return []
 
         # NB. we avoid random getattrs and peek in the __dict__ instead
         # (XXX originally introduced from a PyPy need, still true?)
-        dicts = [getattr(self.obj, '__dict__', {})]
+        dicts = [getattr(self.obj, "__dict__", {})]
         for basecls in inspect.getmro(self.obj.__class__):
             dicts.append(basecls.__dict__)
         seen = {}
         values = []
         for dic in dicts:
             for name, obj in list(dic.items()):
                 if name in seen:
                     continue
@@ -341,92 +399,102 @@ class PyCollector(PyobjMixin, main.Colle
         return values
 
     def makeitem(self, name, obj):
         warnings.warn(deprecated.COLLECTOR_MAKEITEM, stacklevel=2)
         self._makeitem(name, obj)
 
     def _makeitem(self, name, obj):
         # assert self.ihook.fspath == self.fspath, self
-        return self.ihook.pytest_pycollect_makeitem(
-            collector=self, name=name, obj=obj)
+        return self.ihook.pytest_pycollect_makeitem(collector=self, name=name, obj=obj)
 
     def _genfunctions(self, name, funcobj):
         module = self.getparent(Module).obj
         clscol = self.getparent(Class)
         cls = clscol and clscol.obj or None
         transfer_markers(funcobj, cls, module)
         fm = self.session._fixturemanager
-        fixtureinfo = fm.getfixtureinfo(self, funcobj, cls)
-        metafunc = Metafunc(funcobj, fixtureinfo, self.config,
-                            cls=cls, module=module)
+
+        definition = FunctionDefinition(name=name, parent=self, callobj=funcobj)
+        fixtureinfo = fm.getfixtureinfo(definition, funcobj, cls)
+
+        metafunc = Metafunc(
+            definition, fixtureinfo, self.config, cls=cls, module=module
+        )
         methods = []
         if hasattr(module, "pytest_generate_tests"):
             methods.append(module.pytest_generate_tests)
         if hasattr(cls, "pytest_generate_tests"):
             methods.append(cls().pytest_generate_tests)
         if methods:
-            self.ihook.pytest_generate_tests.call_extra(methods,
-                                                        dict(metafunc=metafunc))
+            self.ihook.pytest_generate_tests.call_extra(
+                methods, dict(metafunc=metafunc)
+            )
         else:
             self.ihook.pytest_generate_tests(metafunc=metafunc)
 
         Function = self._getcustomclass("Function")
         if not metafunc._calls:
             yield Function(name, parent=self, fixtureinfo=fixtureinfo)
         else:
             # add funcargs() as fixturedefs to fixtureinfo.arg2fixturedefs
             fixtures.add_funcarg_pseudo_fixture_def(self, metafunc, fm)
 
             for callspec in metafunc._calls:
                 subname = "%s[%s]" % (name, callspec.id)
-                yield Function(name=subname, parent=self,
-                               callspec=callspec, callobj=funcobj,
-                               fixtureinfo=fixtureinfo,
-                               keywords={callspec.id: True},
-                               originalname=name,
-                               )
+                yield Function(
+                    name=subname,
+                    parent=self,
+                    callspec=callspec,
+                    callobj=funcobj,
+                    fixtureinfo=fixtureinfo,
+                    keywords={callspec.id: True},
+                    originalname=name,
+                )
 
 
-class Module(main.File, PyCollector):
+class Module(nodes.File, PyCollector):
     """ Collector for test classes and functions. """
 
     def _getobj(self):
         return self._importtestmodule()
 
     def collect(self):
         self.session._fixturemanager.parsefactories(self)
         return super(Module, self).collect()
 
     def _importtestmodule(self):
         # we assume we are only called once per module
         importmode = self.config.getoption("--import-mode")
         try:
             mod = self.fspath.pyimport(ensuresyspath=importmode)
         except SyntaxError:
             raise self.CollectError(
-                _pytest._code.ExceptionInfo().getrepr(style="short"))
+                _pytest._code.ExceptionInfo().getrepr(style="short")
+            )
         except self.fspath.ImportMismatchError:
             e = sys.exc_info()[1]
             raise self.CollectError(
                 "import file mismatch:\n"
                 "imported module %r has this __file__ attribute:\n"
                 "  %s\n"
                 "which is not the same as the test file we want to collect:\n"
                 "  %s\n"
                 "HINT: remove __pycache__ / .pyc files and/or use a "
-                "unique basename for your test file modules"
-                % e.args
+                "unique basename for your test file modules" % e.args
             )
         except ImportError:
             from _pytest._code.code import ExceptionInfo
+
             exc_info = ExceptionInfo()
-            if self.config.getoption('verbose') < 2:
+            if self.config.getoption("verbose") < 2:
                 exc_info.traceback = exc_info.traceback.filter(filter_traceback)
-            exc_repr = exc_info.getrepr(style='short') if exc_info.traceback else exc_info.exconly()
+            exc_repr = exc_info.getrepr(
+                style="short"
+            ) if exc_info.traceback else exc_info.exconly()
             formatted_tb = safe_str(exc_repr)
             raise self.CollectError(
                 "ImportError while importing test module '{fspath}'.\n"
                 "Hint: make sure your test modules/packages have valid Python names.\n"
                 "Traceback:\n"
                 "{traceback}".format(fspath=self.fspath, traceback=formatted_tb)
             )
         except _pytest.runner.Skipped as e:
@@ -443,19 +511,19 @@ class Module(main.File, PyCollector):
 
     def setup(self):
         setup_module = _get_xunit_setup_teardown(self.obj, "setUpModule")
         if setup_module is None:
             setup_module = _get_xunit_setup_teardown(self.obj, "setup_module")
         if setup_module is not None:
             setup_module()
 
-        teardown_module = _get_xunit_setup_teardown(self.obj, 'tearDownModule')
+        teardown_module = _get_xunit_setup_teardown(self.obj, "tearDownModule")
         if teardown_module is None:
-            teardown_module = _get_xunit_setup_teardown(self.obj, 'teardown_module')
+            teardown_module = _get_xunit_setup_teardown(self.obj, "teardown_module")
         if teardown_module is not None:
             self.addfinalizer(teardown_module)
 
 
 def _get_xunit_setup_teardown(holder, attr_name, param_obj=None):
     """
     Return a callable to perform xunit-style setup or teardown if
     the function exists in the ``holder`` object.
@@ -487,40 +555,51 @@ def _get_xunit_func(obj, name):
 
 class Class(PyCollector):
     """ Collector for test methods. """
 
     def collect(self):
         if not safe_getattr(self.obj, "__test__", True):
             return []
         if hasinit(self.obj):
-            self.warn("C1", "cannot collect test class %r because it has a "
-                      "__init__ constructor" % self.obj.__name__)
+            self.warn(
+                "C1",
+                "cannot collect test class %r because it has a "
+                "__init__ constructor" % self.obj.__name__,
+            )
             return []
         elif hasnew(self.obj):
-            self.warn("C1", "cannot collect test class %r because it has a "
-                            "__new__ constructor" % self.obj.__name__)
+            self.warn(
+                "C1",
+                "cannot collect test class %r because it has a "
+                "__new__ constructor" % self.obj.__name__,
+            )
             return []
         return [self._getcustomclass("Instance")(name="()", parent=self)]
 
     def setup(self):
-        setup_class = _get_xunit_func(self.obj, 'setup_class')
+        setup_class = _get_xunit_func(self.obj, "setup_class")
         if setup_class is not None:
-            setup_class = getattr(setup_class, 'im_func', setup_class)
-            setup_class = getattr(setup_class, '__func__', setup_class)
+            setup_class = getattr(setup_class, "im_func", setup_class)
+            setup_class = getattr(setup_class, "__func__", setup_class)
             setup_class(self.obj)
 
-        fin_class = getattr(self.obj, 'teardown_class', None)
+        fin_class = getattr(self.obj, "teardown_class", None)
         if fin_class is not None:
-            fin_class = getattr(fin_class, 'im_func', fin_class)
-            fin_class = getattr(fin_class, '__func__', fin_class)
+            fin_class = getattr(fin_class, "im_func", fin_class)
+            fin_class = getattr(fin_class, "__func__", fin_class)
             self.addfinalizer(lambda: fin_class(self.obj))
 
 
 class Instance(PyCollector):
+    _ALLOW_MARKERS = False  # hack, destroy later
+    # instances share the object with their parents in a way
+    # that duplicates markers instances if not taken out
+    # can be removed at node strucutre reorganization time
+
     def _getobj(self):
         return self.parent.obj()
 
     def collect(self):
         self.session._fixturemanager.parsefactories(self)
         return super(Instance, self).collect()
 
     def newinstance(self):
@@ -529,125 +608,132 @@ class Instance(PyCollector):
 
 
 class FunctionMixin(PyobjMixin):
     """ mixin for the code common to Function and Generator.
     """
 
     def setup(self):
         """ perform setup for this test function. """
-        if hasattr(self, '_preservedparent'):
+        if hasattr(self, "_preservedparent"):
             obj = self._preservedparent
         elif isinstance(self.parent, Instance):
             obj = self.parent.newinstance()
             self.obj = self._getobj()
         else:
             obj = self.parent.obj
         if inspect.ismethod(self.obj):
-            setup_name = 'setup_method'
-            teardown_name = 'teardown_method'
+            setup_name = "setup_method"
+            teardown_name = "teardown_method"
         else:
-            setup_name = 'setup_function'
-            teardown_name = 'teardown_function'
-        setup_func_or_method = _get_xunit_setup_teardown(obj, setup_name, param_obj=self.obj)
+            setup_name = "setup_function"
+            teardown_name = "teardown_function"
+        setup_func_or_method = _get_xunit_setup_teardown(
+            obj, setup_name, param_obj=self.obj
+        )
         if setup_func_or_method is not None:
             setup_func_or_method()
-        teardown_func_or_method = _get_xunit_setup_teardown(obj, teardown_name, param_obj=self.obj)
+        teardown_func_or_method = _get_xunit_setup_teardown(
+            obj, teardown_name, param_obj=self.obj
+        )
         if teardown_func_or_method is not None:
             self.addfinalizer(teardown_func_or_method)
 
     def _prunetraceback(self, excinfo):
-        if hasattr(self, '_obj') and not self.config.option.fulltrace:
+        if hasattr(self, "_obj") and not self.config.option.fulltrace:
             code = _pytest._code.Code(get_real_func(self.obj))
             path, firstlineno = code.path, code.firstlineno
             traceback = excinfo.traceback
             ntraceback = traceback.cut(path=path, firstlineno=firstlineno)
             if ntraceback == traceback:
                 ntraceback = ntraceback.cut(path=path)
                 if ntraceback == traceback:
-                    # ntraceback = ntraceback.cut(excludepath=cutdir2)
                     ntraceback = ntraceback.filter(filter_traceback)
                     if not ntraceback:
                         ntraceback = traceback
 
             excinfo.traceback = ntraceback.filter()
             # issue364: mark all but first and last frames to
             # only show a single-line message for each frame
             if self.config.option.tbstyle == "auto":
                 if len(excinfo.traceback) > 2:
                     for entry in excinfo.traceback[1:-1]:
-                        entry.set_repr_style('short')
+                        entry.set_repr_style("short")
 
     def _repr_failure_py(self, excinfo, style="long"):
         if excinfo.errisinstance(fail.Exception):
             if not excinfo.value.pytrace:
                 return py._builtin._totext(excinfo.value)
-        return super(FunctionMixin, self)._repr_failure_py(excinfo,
-                                                           style=style)
+        return super(FunctionMixin, self)._repr_failure_py(excinfo, style=style)
 
     def repr_failure(self, excinfo, outerr=None):
         assert outerr is None, "XXX outerr usage is deprecated"
         style = self.config.option.tbstyle
         if style == "auto":
             style = "long"
         return self._repr_failure_py(excinfo, style=style)
 
 
 class Generator(FunctionMixin, PyCollector):
+
     def collect(self):
         # test generators are seen as collectors but they also
         # invoke setup/teardown on popular request
         # (induced by the common "test_*" naming shared with normal tests)
         from _pytest import deprecated
+
         self.session._setupstate.prepare(self)
         # see FunctionMixin.setup and test_setupstate_is_preserved_134
         self._preservedparent = self.parent.obj
         values = []
         seen = {}
         for i, x in enumerate(self.obj()):
             name, call, args = self.getcallargs(x)
             if not callable(call):
-                raise TypeError("%r yielded non callable test %r" % (self.obj, call,))
+                raise TypeError("%r yielded non callable test %r" % (self.obj, call))
             if name is None:
                 name = "[%d]" % i
             else:
                 name = "['%s']" % name
             if name in seen:
-                raise ValueError("%r generated tests with non-unique name %r" % (self, name))
+                raise ValueError(
+                    "%r generated tests with non-unique name %r" % (self, name)
+                )
             seen[name] = True
             values.append(self.Function(name, self, args=args, callobj=call))
-        self.warn('C1', deprecated.YIELD_TESTS)
+        self.warn("C1", deprecated.YIELD_TESTS)
         return values
 
     def getcallargs(self, obj):
         if not isinstance(obj, (tuple, list)):
             obj = (obj,)
         # explicit naming
         if isinstance(obj[0], six.string_types):
             name = obj[0]
             obj = obj[1:]
         else:
             name = None
         call, args = obj[0], obj[1:]
         return name, call, args
 
 
 def hasinit(obj):
-    init = getattr(obj, '__init__', None)
+    init = getattr(obj, "__init__", None)
     if init:
         return init != object.__init__
 
 
 def hasnew(obj):
-    new = getattr(obj, '__new__', None)
+    new = getattr(obj, "__new__", None)
     if new:
         return new != object.__new__
 
 
 class CallSpec2(object):
+
     def __init__(self, metafunc):
         self.metafunc = metafunc
         self.funcargs = {}
         self._idlist = []
         self.params = {}
         self._globalid = NOTSET
         self._globalid_args = set()
         self._globalparam = NOTSET
@@ -679,18 +765,17 @@ class CallSpec2(object):
             if self._globalparam is NOTSET:
                 raise ValueError(name)
             return self._globalparam
 
     @property
     def id(self):
         return "-".join(map(str, filter(None, self._idlist)))
 
-    def setmulti2(self, valtypes, argnames, valset, id, marks, scopenum,
-                  param_index):
+    def setmulti2(self, valtypes, argnames, valset, id, marks, scopenum, param_index):
         for arg, val in zip(argnames, valset):
             self._checkargnotcontained(arg)
             valtype_for_arg = valtypes[arg]
             getattr(self, valtype_for_arg)[arg] = val
             self.indices[arg] = param_index
             self._arg2scopenum[arg] = scopenum
         self._idlist.append(id)
         self.marks.extend(marks)
@@ -705,44 +790,48 @@ class CallSpec2(object):
             assert self._globalparam is NOTSET
             self._globalparam = param
         for arg in funcargs:
             self._arg2scopenum[arg] = fixtures.scopenum_function
 
 
 class Metafunc(fixtures.FuncargnamesCompatAttr):
     """
-    Metafunc objects are passed to the ``pytest_generate_tests`` hook.
+    Metafunc objects are passed to the :func:`pytest_generate_tests <_pytest.hookspec.pytest_generate_tests>` hook.
     They help to inspect a test function and to generate tests according to
     test configuration or values specified in the class or module where a
     test function is defined.
     """
 
-    def __init__(self, function, fixtureinfo, config, cls=None, module=None):
+    def __init__(self, definition, fixtureinfo, config, cls=None, module=None):
         #: access to the :class:`_pytest.config.Config` object for the test session
+        assert (
+            isinstance(definition, FunctionDefinition)
+            or type(definition).__name__ == "DefinitionMock"
+        )
+        self.definition = definition
         self.config = config
 
         #: the module object where the test function is defined in.
         self.module = module
 
         #: underlying python test function
-        self.function = function
+        self.function = definition.obj
 
         #: set of fixture names required by the test function
         self.fixturenames = fixtureinfo.names_closure
 
         #: class object where the test function is defined in or ``None``.
         self.cls = cls
 
         self._calls = []
         self._ids = set()
         self._arg2fixturedefs = fixtureinfo.name2fixturedefs
 
-    def parametrize(self, argnames, argvalues, indirect=False, ids=None,
-                    scope=None):
+    def parametrize(self, argnames, argvalues, indirect=False, ids=None, scope=None):
         """ Add new invocations to the underlying test function using the list
         of argvalues for the given argnames.  Parametrization is performed
         during the collection phase.  If you need to setup expensive resources
         see about setting indirect to do it rather at test setup time.
 
         :arg argnames: a comma-separated string denoting one or more argument
                        names, or a list/tuple of argument strings.
 
@@ -773,71 +862,92 @@ class Metafunc(fixtures.FuncargnamesComp
         :arg scope: if specified it denotes the scope of the parameters.
             The scope is used for grouping tests by parameter instances.
             It will also override any fixture-function defined scope, allowing
             to set a dynamic scope using test context or configuration.
         """
         from _pytest.fixtures import scope2index
         from _pytest.mark import ParameterSet
         from py.io import saferepr
-        argnames, parameters = ParameterSet._for_parameterize(
-            argnames, argvalues, self.function)
+
+        argnames, parameters = ParameterSet._for_parametrize(
+            argnames, argvalues, self.function, self.config
+        )
         del argvalues
+        default_arg_names = set(get_default_arg_names(self.function))
 
         if scope is None:
             scope = _find_parametrized_scope(argnames, self._arg2fixturedefs, indirect)
 
-        scopenum = scope2index(scope, descr='call to {0}'.format(self.parametrize))
+        scopenum = scope2index(scope, descr="call to {}".format(self.parametrize))
         valtypes = {}
         for arg in argnames:
             if arg not in self.fixturenames:
-                if isinstance(indirect, (tuple, list)):
-                    name = 'fixture' if arg in indirect else 'argument'
+                if arg in default_arg_names:
+                    raise ValueError(
+                        "%r already takes an argument %r with a default value"
+                        % (self.function, arg)
+                    )
                 else:
-                    name = 'fixture' if indirect else 'argument'
-                raise ValueError(
-                    "%r uses no %s %r" % (
-                        self.function, name, arg))
+                    if isinstance(indirect, (tuple, list)):
+                        name = "fixture" if arg in indirect else "argument"
+                    else:
+                        name = "fixture" if indirect else "argument"
+                    raise ValueError("%r uses no %s %r" % (self.function, name, arg))
 
         if indirect is True:
             valtypes = dict.fromkeys(argnames, "params")
         elif indirect is False:
             valtypes = dict.fromkeys(argnames, "funcargs")
         elif isinstance(indirect, (tuple, list)):
             valtypes = dict.fromkeys(argnames, "funcargs")
             for arg in indirect:
                 if arg not in argnames:
-                    raise ValueError("indirect given to %r: fixture %r doesn't exist" % (
-                                     self.function, arg))
+                    raise ValueError(
+                        "indirect given to %r: fixture %r doesn't exist"
+                        % (self.function, arg)
+                    )
                 valtypes[arg] = "params"
         idfn = None
         if callable(ids):
             idfn = ids
             ids = None
         if ids:
             if len(ids) != len(parameters):
-                raise ValueError('%d tests specified with %d ids' % (
-                                 len(parameters), len(ids)))
+                raise ValueError(
+                    "%d tests specified with %d ids" % (len(parameters), len(ids))
+                )
             for id_value in ids:
                 if id_value is not None and not isinstance(id_value, six.string_types):
-                    msg = 'ids must be list of strings, found: %s (type: %s)'
-                    raise ValueError(msg % (saferepr(id_value), type(id_value).__name__))
+                    msg = "ids must be list of strings, found: %s (type: %s)"
+                    raise ValueError(
+                        msg % (saferepr(id_value), type(id_value).__name__)
+                    )
         ids = idmaker(argnames, parameters, idfn, ids, self.config)
         newcalls = []
         for callspec in self._calls or [CallSpec2(self)]:
             elements = zip(ids, parameters, count())
             for a_id, param, param_index in elements:
                 if len(param.values) != len(argnames):
                     raise ValueError(
-                        'In "parametrize" the number of values ({0}) must be '
-                        'equal to the number of names ({1})'.format(
-                            param.values, argnames))
+                        'In "parametrize" the number of values ({}) must be '
+                        "equal to the number of names ({})".format(
+                            param.values, argnames
+                        )
+                    )
                 newcallspec = callspec.copy(self)
-                newcallspec.setmulti2(valtypes, argnames, param.values, a_id,
-                                      param.marks, scopenum, param_index)
+                newcallspec.setmulti2(
+                    valtypes,
+                    argnames,
+                    param.values,
+                    a_id,
+                    param.marks,
+                    scopenum,
+                    param_index,
+                )
                 newcalls.append(newcallspec)
         self._calls = newcalls
 
     def addcall(self, funcargs=None, id=NOTSET, param=NOTSET):
         """ Add a new call to the underlying test function during the collection phase of a test run.
 
         .. deprecated:: 3.3
 
@@ -852,17 +962,19 @@ class Metafunc(fixtures.FuncargnamesComp
 
         :arg id: used for reporting and identification purposes.  If you
             don't supply an `id` an automatic unique id will be generated.
 
         :arg param: a parameter which will be exposed to a later fixture function
             invocation through the ``request.param`` attribute.
         """
         if self.config:
-            self.config.warn('C1', message=deprecated.METAFUNC_ADD_CALL, fslocation=None)
+            self.config.warn(
+                "C1", message=deprecated.METAFUNC_ADD_CALL, fslocation=None
+            )
         assert funcargs is None or isinstance(funcargs, dict)
         if funcargs is not None:
             for name in funcargs:
                 if name not in self.fixturenames:
                     fail("funcarg %r not used in this function." % name)
         else:
             funcargs = {}
         if id is None:
@@ -885,152 +997,166 @@ def _find_parametrized_scope(argnames, a
     When there's at least one direct argument, always use "function" scope.
 
     When a test function is parametrized and all its arguments are indirect
     (e.g. fixtures), return the most narrow scope based on the fixtures used.
 
     Related to issue #1832, based on code posted by @Kingdread.
     """
     from _pytest.fixtures import scopes
+
     indirect_as_list = isinstance(indirect, (list, tuple))
-    all_arguments_are_fixtures = indirect is True or \
-        indirect_as_list and len(indirect) == argnames
+    all_arguments_are_fixtures = indirect is True or indirect_as_list and len(
+        indirect
+    ) == argnames
     if all_arguments_are_fixtures:
         fixturedefs = arg2fixturedefs or {}
         used_scopes = [fixturedef[0].scope for name, fixturedef in fixturedefs.items()]
         if used_scopes:
             # Takes the most narrow scope from used fixtures
             for scope in reversed(scopes):
                 if scope in used_scopes:
                     return scope
 
-    return 'function'
+    return "function"
 
 
 def _idval(val, argname, idx, idfn, config=None):
     if idfn:
         s = None
         try:
             s = idfn(val)
         except Exception:
             # See issue https://github.com/pytest-dev/pytest/issues/2169
             import warnings
-            msg = "Raised while trying to determine id of parameter %s at position %d." % (argname, idx)
-            msg += '\nUpdate your code as this will raise an error in pytest-4.0.'
+
+            msg = "Raised while trying to determine id of parameter %s at position %d." % (
+                argname, idx
+            )
+            msg += "\nUpdate your code as this will raise an error in pytest-4.0."
             warnings.warn(msg, DeprecationWarning)
         if s:
             return ascii_escaped(s)
 
     if config:
         hook_id = config.hook.pytest_make_parametrize_id(
-            config=config, val=val, argname=argname)
+            config=config, val=val, argname=argname
+        )
         if hook_id:
             return hook_id
 
     if isinstance(val, STRING_TYPES):
         return ascii_escaped(val)
     elif isinstance(val, (float, int, bool, NoneType)):
         return str(val)
     elif isinstance(val, REGEX_TYPE):
         return ascii_escaped(val.pattern)
     elif enum is not None and isinstance(val, enum.Enum):
         return str(val)
-    elif isclass(val) and hasattr(val, '__name__'):
+    elif (isclass(val) or isfunction(val)) and hasattr(val, "__name__"):
         return val.__name__
     return str(argname) + str(idx)
 
 
 def _idvalset(idx, parameterset, argnames, idfn, ids, config=None):
     if parameterset.id is not None:
         return parameterset.id
     if ids is None or (idx >= len(ids) or ids[idx] is None):
-        this_id = [_idval(val, argname, idx, idfn, config)
-                   for val, argname in zip(parameterset.values, argnames)]
+        this_id = [
+            _idval(val, argname, idx, idfn, config)
+            for val, argname in zip(parameterset.values, argnames)
+        ]
         return "-".join(this_id)
     else:
         return ascii_escaped(ids[idx])
 
 
 def idmaker(argnames, parametersets, idfn=None, ids=None, config=None):
-    ids = [_idvalset(valindex, parameterset, argnames, idfn, ids, config)
-           for valindex, parameterset in enumerate(parametersets)]
+    ids = [
+        _idvalset(valindex, parameterset, argnames, idfn, ids, config)
+        for valindex, parameterset in enumerate(parametersets)
+    ]
     if len(set(ids)) != len(ids):
         # The ids are not unique
         duplicates = [testid for testid in ids if ids.count(testid) > 1]
         counters = collections.defaultdict(lambda: 0)
         for index, testid in enumerate(ids):
             if testid in duplicates:
                 ids[index] = testid + str(counters[testid])
                 counters[testid] += 1
     return ids
 
 
 def show_fixtures_per_test(config):
     from _pytest.main import wrap_session
+
     return wrap_session(config, _show_fixtures_per_test)
 
 
 def _show_fixtures_per_test(config, session):
     import _pytest.config
+
     session.perform_collect()
     curdir = py.path.local()
     tw = _pytest.config.create_terminal_writer(config)
     verbose = config.getvalue("verbose")
 
     def get_best_relpath(func):
         loc = getlocation(func, curdir)
         return curdir.bestrelpath(loc)
 
     def write_fixture(fixture_def):
         argname = fixture_def.argname
         if verbose <= 0 and argname.startswith("_"):
             return
         if verbose > 0:
             bestrel = get_best_relpath(fixture_def.func)
-            funcargspec = "{0} -- {1}".format(argname, bestrel)
+            funcargspec = "{} -- {}".format(argname, bestrel)
         else:
             funcargspec = argname
         tw.line(funcargspec, green=True)
         fixture_doc = fixture_def.func.__doc__
         if fixture_doc:
             write_docstring(tw, fixture_doc)
         else:
-            tw.line('    no docstring available', red=True)
+            tw.line("    no docstring available", red=True)
 
     def write_item(item):
         try:
             info = item._fixtureinfo
         except AttributeError:
             # doctests items have no _fixtureinfo attribute
             return
         if not info.name2fixturedefs:
             # this test item does not use any fixtures
             return
         tw.line()
-        tw.sep('-', 'fixtures used by {0}'.format(item.name))
-        tw.sep('-', '({0})'.format(get_best_relpath(item.function)))
+        tw.sep("-", "fixtures used by {}".format(item.name))
+        tw.sep("-", "({})".format(get_best_relpath(item.function)))
         # dict key not used in loop but needed for sorting
         for _, fixturedefs in sorted(info.name2fixturedefs.items()):
             assert fixturedefs is not None
             if not fixturedefs:
                 continue
             # last item is expected to be the one used by the test item
             write_fixture(fixturedefs[-1])
 
     for session_item in session.items:
         write_item(session_item)
 
 
 def showfixtures(config):
     from _pytest.main import wrap_session
+
     return wrap_session(config, _showfixtures_main)
 
 
 def _showfixtures_main(config, session):
     import _pytest.config
+
     session.perform_collect()
     curdir = py.path.local()
     tw = _pytest.config.create_terminal_writer(config)
     verbose = config.getvalue("verbose")
 
     fm = session._fixturemanager
 
     available = []
@@ -1040,43 +1166,47 @@ def _showfixtures_main(config, session):
         assert fixturedefs is not None
         if not fixturedefs:
             continue
         for fixturedef in fixturedefs:
             loc = getlocation(fixturedef.func, curdir)
             if (fixturedef.argname, loc) in seen:
                 continue
             seen.add((fixturedef.argname, loc))
-            available.append((len(fixturedef.baseid),
-                              fixturedef.func.__module__,
-                              curdir.bestrelpath(loc),
-                              fixturedef.argname, fixturedef))
+            available.append(
+                (
+                    len(fixturedef.baseid),
+                    fixturedef.func.__module__,
+                    curdir.bestrelpath(loc),
+                    fixturedef.argname,
+                    fixturedef,
+                )
+            )
 
     available.sort()
     currentmodule = None
     for baseid, module, bestrel, argname, fixturedef in available:
         if currentmodule != module:
             if not module.startswith("_pytest."):
                 tw.line()
                 tw.sep("-", "fixtures defined from %s" % (module,))
                 currentmodule = module
         if verbose <= 0 and argname[0] == "_":
             continue
         if verbose > 0:
-            funcargspec = "%s -- %s" % (argname, bestrel,)
+            funcargspec = "%s -- %s" % (argname, bestrel)
         else:
             funcargspec = argname
         tw.line(funcargspec, green=True)
         loc = getlocation(fixturedef.func, curdir)
         doc = fixturedef.func.__doc__ or ""
         if doc:
             write_docstring(tw, doc)
         else:
-            tw.line("    %s: no docstring available" % (loc,),
-                    red=True)
+            tw.line("    %s: no docstring available" % (loc,), red=True)
 
 
 def write_docstring(tw, doc):
     INDENT = "    "
     doc = doc.rstrip()
     if "\n" in doc:
         firstline, rest = doc.split("\n", 1)
     else:
@@ -1085,76 +1215,90 @@ def write_docstring(tw, doc):
     if firstline.strip():
         tw.line(INDENT + firstline.strip())
 
     if rest:
         for line in dedent(rest).split("\n"):
             tw.write(INDENT + line + "\n")
 
 
-class Function(FunctionMixin, main.Item, fixtures.FuncargnamesCompatAttr):
+class Function(FunctionMixin, nodes.Item, fixtures.FuncargnamesCompatAttr):
     """ a Function Item is responsible for setting up and executing a
     Python test function.
     """
     _genid = None
+    # disable since functions handle it themselfes
+    _ALLOW_MARKERS = False
 
-    def __init__(self, name, parent, args=None, config=None,
-                 callspec=None, callobj=NOTSET, keywords=None, session=None,
-                 fixtureinfo=None, originalname=None):
-        super(Function, self).__init__(name, parent, config=config,
-                                       session=session)
+    def __init__(
+        self,
+        name,
+        parent,
+        args=None,
+        config=None,
+        callspec=None,
+        callobj=NOTSET,
+        keywords=None,
+        session=None,
+        fixtureinfo=None,
+        originalname=None,
+    ):
+        super(Function, self).__init__(name, parent, config=config, session=session)
         self._args = args
         if callobj is not NOTSET:
             self.obj = callobj
 
         self.keywords.update(self.obj.__dict__)
+        self.own_markers.extend(get_unpacked_marks(self.obj))
         if callspec:
             self.callspec = callspec
             # this is total hostile and a mess
             # keywords are broken by design by now
             # this will be redeemed later
             for mark in callspec.marks:
                 # feel free to cry, this was broken for years before
                 # and keywords cant fix it per design
                 self.keywords[mark.name] = mark
+            self.own_markers.extend(callspec.marks)
         if keywords:
             self.keywords.update(keywords)
 
         if fixtureinfo is None:
             fixtureinfo = self.session._fixturemanager.getfixtureinfo(
-                self.parent, self.obj, self.cls,
-                funcargs=not self._isyieldedfunction())
+                self, self.obj, self.cls, funcargs=not self._isyieldedfunction()
+            )
         self._fixtureinfo = fixtureinfo
         self.fixturenames = fixtureinfo.names_closure
         self._initrequest()
 
         #: original function name, without any decorations (for example
         #: parametrization adds a ``"[...]"`` suffix to function names).
         #:
         #: .. versionadded:: 3.0
         self.originalname = originalname
 
     def _initrequest(self):
         self.funcargs = {}
         if self._isyieldedfunction():
-            assert not hasattr(self, "callspec"), (
-                "yielded functions (deprecated) cannot have funcargs")
+            assert not hasattr(
+                self, "callspec"
+            ), "yielded functions (deprecated) cannot have funcargs"
         else:
             if hasattr(self, "callspec"):
                 callspec = self.callspec
                 assert not callspec.funcargs
                 self._genid = callspec.id
                 if hasattr(callspec, "param"):
                     self.param = callspec.param
         self._request = fixtures.FixtureRequest(self)
 
     @property
     def function(self):
         "underlying python 'function' object"
-        return getattr(self.obj, 'im_func', self.obj)
+        return getattr(self.obj, "im_func", self.obj)
 
     def _getobj(self):
         name = self.name
         i = name.find("[")  # parametrization
         if i != -1:
             name = name[:i]
         return getattr(self.parent.obj, name)
 
@@ -1168,8 +1312,20 @@ class Function(FunctionMixin, main.Item,
 
     def runtest(self):
         """ execute the underlying test function. """
         self.ihook.pytest_pyfunc_call(pyfuncitem=self)
 
     def setup(self):
         super(Function, self).setup()
         fixtures.fillfixtures(self)
+
+
+class FunctionDefinition(Function):
+    """
+    internal hack until we get actual definition nodes instead of the
+    crappy metafunc hack
+    """
+
+    def runtest(self):
+        raise RuntimeError("function definitions are not supposed to be used")
+
+    setup = runtest
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/python_api.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/python_api.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/python_api.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/python_api.py
@@ -1,53 +1,66 @@
 import math
 import sys
 
 import py
-from six.moves import zip
+from six.moves import zip, filterfalse
+from more_itertools.more import always_iterable
 
 from _pytest.compat import isclass
+
+from _pytest.compat import Mapping, Sequence
+from _pytest.compat import STRING_TYPES
+
 from _pytest.outcomes import fail
 import _pytest._code
 
+BASE_TYPE = (type, STRING_TYPES)
+
 
 def _cmp_raises_type_error(self, other):
     """__cmp__ implementation which raises TypeError. Used
     by Approx base classes to implement only == and != and raise a
     TypeError for other comparisons.
 
     Needed in Python 2 only, Python 3 all it takes is not implementing the
     other operators at all.
     """
     __tracebackhide__ = True
-    raise TypeError('Comparison operators other than == and != not supported by approx objects')
+    raise TypeError(
+        "Comparison operators other than == and != not supported by approx objects"
+    )
 
 
 # builtin pytest.approx helper
 
 
 class ApproxBase(object):
     """
     Provide shared utilities for making approximate comparisons between numbers
     or sequences of numbers.
     """
 
+    # Tell numpy to use our `__eq__` operator instead of its
+    __array_ufunc__ = None
+    __array_priority__ = 100
+
     def __init__(self, expected, rel=None, abs=None, nan_ok=False):
         self.expected = expected
         self.abs = abs
         self.rel = rel
         self.nan_ok = nan_ok
 
     def __repr__(self):
         raise NotImplementedError
 
     def __eq__(self, actual):
         return all(
-            a == self._approx_scalar(x)
-            for a, x in self._yield_comparisons(actual))
+            a == self._approx_scalar(x) for a, x in self._yield_comparisons(actual)
+        )
 
     __hash__ = None
 
     def __ne__(self, actual):
         return not (actual == self)
 
     if sys.version_info[0] == 2:
         __cmp__ = _cmp_raises_type_error
@@ -63,61 +76,69 @@ class ApproxBase(object):
         raise NotImplementedError
 
 
 class ApproxNumpy(ApproxBase):
     """
     Perform approximate comparisons for numpy arrays.
     """
 
-    # Tell numpy to use our `__eq__` operator instead of its.
-    __array_priority__ = 100
-
     def __repr__(self):
         # It might be nice to rewrite this function to account for the
         # shape of the array...
-        return "approx({0!r})".format(list(
-            self._approx_scalar(x) for x in self.expected))
+        import numpy as np
+
+        return "approx({!r})".format(
+            list(self._approx_scalar(x) for x in np.asarray(self.expected))
+        )
 
     if sys.version_info[0] == 2:
         __cmp__ = _cmp_raises_type_error
 
     def __eq__(self, actual):
         import numpy as np
 
-        try:
-            actual = np.asarray(actual)
-        except:  # noqa
-            raise TypeError("cannot compare '{0}' to numpy.ndarray".format(actual))
+        # self.expected is supposed to always be an array here
 
-        if actual.shape != self.expected.shape:
+        if not np.isscalar(actual):
+            try:
+                actual = np.asarray(actual)
+            except:  # noqa
+                raise TypeError("cannot compare '{}' to numpy.ndarray".format(actual))
+
+        if not np.isscalar(actual) and actual.shape != self.expected.shape:
             return False
 
         return ApproxBase.__eq__(self, actual)
 
     def _yield_comparisons(self, actual):
         import numpy as np
 
-        # We can be sure that `actual` is a numpy array, because it's
-        # casted in `__eq__` before being passed to `ApproxBase.__eq__`,
-        # which is the only method that calls this one.
-        for i in np.ndindex(self.expected.shape):
-            yield actual[i], self.expected[i]
+        # `actual` can either be a numpy array or a scalar, it is treated in
+        # `__eq__` before being passed to `ApproxBase.__eq__`, which is the
+        # only method that calls this one.
+
+        if np.isscalar(actual):
+            for i in np.ndindex(self.expected.shape):
+                yield actual, np.asscalar(self.expected[i])
+        else:
+            for i in np.ndindex(self.expected.shape):
+                yield np.asscalar(actual[i]), np.asscalar(self.expected[i])
 
 
 class ApproxMapping(ApproxBase):
     """
     Perform approximate comparisons for mappings where the values are numbers
     (the keys can be anything).
     """
 
     def __repr__(self):
-        return "approx({0!r})".format(dict(
-            (k, self._approx_scalar(v))
-            for k, v in self.expected.items()))
+        return "approx({!r})".format(
+            {k: self._approx_scalar(v) for k, v in self.expected.items()}
+        )
 
     def __eq__(self, actual):
         if set(actual.keys()) != set(self.expected.keys()):
             return False
 
         return ApproxBase.__eq__(self, actual)
 
     def _yield_comparisons(self, actual):
@@ -125,39 +146,39 @@ class ApproxMapping(ApproxBase):
             yield actual[k], self.expected[k]
 
 
 class ApproxSequence(ApproxBase):
     """
     Perform approximate comparisons for sequences of numbers.
     """
 
-    # Tell numpy to use our `__eq__` operator instead of its.
-    __array_priority__ = 100
-
     def __repr__(self):
         seq_type = type(self.expected)
         if seq_type not in (tuple, list, set):
             seq_type = list
-        return "approx({0!r})".format(seq_type(
-            self._approx_scalar(x) for x in self.expected))
+        return "approx({!r})".format(
+            seq_type(self._approx_scalar(x) for x in self.expected)
+        )
 
     def __eq__(self, actual):
         if len(actual) != len(self.expected):
             return False
         return ApproxBase.__eq__(self, actual)
 
     def _yield_comparisons(self, actual):
         return zip(actual, self.expected)
 
 
 class ApproxScalar(ApproxBase):
     """
     Perform approximate comparisons for single numbers only.
     """
+    DEFAULT_ABSOLUTE_TOLERANCE = 1e-12
+    DEFAULT_RELATIVE_TOLERANCE = 1e-6
 
     def __repr__(self):
         """
         Return a string communicating both the expected value and the tolerance
         for the comparison being made, e.g. '1.0 +- 1e-6'.  Use the unicode
         plus/minus symbol if this is python3 (it's too hard to get right for
         python2).
         """
@@ -167,30 +188,32 @@ class ApproxScalar(ApproxBase):
         # Infinities aren't compared using tolerances, so don't show a
         # tolerance.
         if math.isinf(self.expected):
             return str(self.expected)
 
         # If a sensible tolerance can't be calculated, self.tolerance will
         # raise a ValueError.  In this case, display '???'.
         try:
-            vetted_tolerance = '{:.1e}'.format(self.tolerance)
+            vetted_tolerance = "{:.1e}".format(self.tolerance)
         except ValueError:
-            vetted_tolerance = '???'
+            vetted_tolerance = "???"
 
         if sys.version_info[0] == 2:
-            return '{0} +- {1}'.format(self.expected, vetted_tolerance)
+            return "{} +- {}".format(self.expected, vetted_tolerance)
         else:
-            return u'{0} \u00b1 {1}'.format(self.expected, vetted_tolerance)
+            return u"{} \u00b1 {}".format(self.expected, vetted_tolerance)
 
     def __eq__(self, actual):
         """
         Return true if the given value is equal to the expected value within
         the pre-specified tolerance.
         """
+        if _is_numpy_array(actual):
+            return ApproxNumpy(actual, self.abs, self.rel, self.nan_ok) == self.expected
 
         # Short-circuit exact equality.
         if actual == self.expected:
             return True
 
         # Allow the user to control whether NaNs are considered equal to each
         # other or not.  The abs() calls are for compatibility with complex
         # numbers.
@@ -213,50 +236,66 @@ class ApproxScalar(ApproxBase):
 
     @property
     def tolerance(self):
         """
         Return the tolerance for the comparison.  This could be either an
         absolute tolerance or a relative tolerance, depending on what the user
         specified or which would be larger.
         """
+
         def set_default(x, default):
             return x if x is not None else default
 
         # Figure out what the absolute tolerance should be.  ``self.abs`` is
         # either None or a value specified by the user.
-        absolute_tolerance = set_default(self.abs, 1e-12)
+        absolute_tolerance = set_default(self.abs, self.DEFAULT_ABSOLUTE_TOLERANCE)
 
         if absolute_tolerance < 0:
-            raise ValueError("absolute tolerance can't be negative: {}".format(absolute_tolerance))
+            raise ValueError(
+                "absolute tolerance can't be negative: {}".format(absolute_tolerance)
+            )
         if math.isnan(absolute_tolerance):
             raise ValueError("absolute tolerance can't be NaN.")
 
         # If the user specified an absolute tolerance but not a relative one,
         # just return the absolute tolerance.
         if self.rel is None:
             if self.abs is not None:
                 return absolute_tolerance
 
         # Figure out what the relative tolerance should be.  ``self.rel`` is
         # either None or a value specified by the user.  This is done after
         # we've made sure the user didn't ask for an absolute tolerance only,
         # because we don't want to raise errors about the relative tolerance if
         # we aren't even going to use it.
-        relative_tolerance = set_default(self.rel, 1e-6) * abs(self.expected)
+        relative_tolerance = set_default(
+            self.rel, self.DEFAULT_RELATIVE_TOLERANCE
+        ) * abs(
+            self.expected
+        )
 
         if relative_tolerance < 0:
-            raise ValueError("relative tolerance can't be negative: {}".format(absolute_tolerance))
+            raise ValueError(
+                "relative tolerance can't be negative: {}".format(absolute_tolerance)
+            )
         if math.isnan(relative_tolerance):
             raise ValueError("relative tolerance can't be NaN.")
 
         # Return the larger of the relative and absolute tolerances.
         return max(relative_tolerance, absolute_tolerance)
 
 
+class ApproxDecimal(ApproxScalar):
+    from decimal import Decimal
+
+    DEFAULT_ABSOLUTE_TOLERANCE = Decimal("1e-12")
+    DEFAULT_RELATIVE_TOLERANCE = Decimal("1e-6")
+
+
 def approx(expected, rel=None, abs=None, nan_ok=False):
     """
     Assert that two numbers (or two sets of numbers) are equal to each other
     within some tolerance.
 
     Due to the `intricacies of floating-point arithmetic`__, numbers that we
     would intuitively expect to be equal are not always so::
 
@@ -293,22 +332,28 @@ def approx(expected, rel=None, abs=None,
         >>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))
         True
 
     Dictionary *values*::
 
         >>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6})
         True
 
-    And ``numpy`` arrays::
+    ``numpy`` arrays::
 
         >>> import numpy as np                                                          # doctest: +SKIP
         >>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) # doctest: +SKIP
         True
 
+    And for a ``numpy`` array against a scalar::
+
+        >>> import numpy as np                                         # doctest: +SKIP
+        >>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) # doctest: +SKIP
+        True
+
     By default, ``approx`` considers numbers within a relative tolerance of
     ``1e-6`` (i.e. one part in a million) of its expected value to be equal.
     This treatment would lead to surprising results if the expected value was
     ``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``.
     To handle this case less surprisingly, ``approx`` also considers numbers
     within an absolute tolerance of ``1e-12`` of its expected value to be
     equal.  Infinity and NaN are special cases.  Infinity is only considered
     equal to itself, regardless of the relative tolerance.  NaN is not
@@ -394,18 +439,17 @@ def approx(expected, rel=None, abs=None,
        In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)``
        to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used to
        comparison. This is because the call hierarchy of rich comparisons
        follows a fixed behavior. `More information...`__
 
        __ https://docs.python.org/3/reference/datamodel.html#object.__ge__
     """
 
-    from collections import Mapping, Sequence
-    from _pytest.compat import STRING_TYPES as String
+    from decimal import Decimal
 
     # Delegate the comparison to a class that knows how to deal with the type
     # of the expected value (e.g. int, float, list, dict, numpy.array, etc).
     #
     # This architecture is really driven by the need to support numpy arrays.
     # The only way to override `==` for arrays without requiring that approx be
     # the left operand is to inherit the approx object from `numpy.ndarray`.
     # But that can't be a general solution, because it requires (1) numpy to be
@@ -415,49 +459,57 @@ def approx(expected, rel=None, abs=None,
     # This has the advantage that it made it easy to support mapping types
     # (i.e. dict).  The old code accepted mapping types, but would only compare
     # their keys, which is probably not what most people would expect.
 
     if _is_numpy_array(expected):
         cls = ApproxNumpy
     elif isinstance(expected, Mapping):
         cls = ApproxMapping
-    elif isinstance(expected, Sequence) and not isinstance(expected, String):
+    elif isinstance(expected, Sequence) and not isinstance(expected, STRING_TYPES):
         cls = ApproxSequence
+    elif isinstance(expected, Decimal):
+        cls = ApproxDecimal
     else:
         cls = ApproxScalar
 
     return cls(expected, rel, abs, nan_ok)
 
 
 def _is_numpy_array(obj):
     """
     Return true if the given object is a numpy array.  Make a special effort to
     avoid importing numpy unless it's really necessary.
     """
     import inspect
 
     for cls in inspect.getmro(type(obj)):
-        if cls.__module__ == 'numpy':
+        if cls.__module__ == "numpy":
             try:
                 import numpy as np
+
                 return isinstance(obj, np.ndarray)
             except ImportError:
                 pass
 
     return False
 
 
 # builtin pytest.raises helper
 
+
 def raises(expected_exception, *args, **kwargs):
-    """
+    r"""
     Assert that a code block/function call raises ``expected_exception``
     and raise a failure exception otherwise.
 
+    :arg message: if specified, provides a custom failure message if the
+        exception is not raised
+    :arg match: if specified, asserts that the exception matches a text or regex
+
     This helper produces a ``ExceptionInfo()`` object (see below).
 
     You may use this function as a context manager::
 
         >>> with raises(ZeroDivisionError):
         ...    1/0
 
     .. versionchanged:: 2.10
@@ -526,18 +578,19 @@ def raises(expected_exception, *args, **
     It is also possible to pass a string to be evaluated at runtime::
 
         >>> raises(ZeroDivisionError, "f(0)")
         <ExceptionInfo ...>
 
     The string will be evaluated using the same ``locals()`` and ``globals()``
     at the moment of the ``raises`` call.
 
-    .. autoclass:: _pytest._code.ExceptionInfo
-        :members:
+    .. currentmodule:: _pytest._code
+
+    Consult the API of ``excinfo`` objects: :class:`ExceptionInfo`.
 
     .. note::
         Similar to caught exception objects in Python, explicitly clearing
         local references to returned ``ExceptionInfo`` objects can
         help the Python interpreter speed up its garbage collection.
 
         Clearing those references breaks a reference cycle
         (``ExceptionInfo`` --> caught exception --> frame stack raising
@@ -545,34 +598,35 @@ def raises(expected_exception, *args, **
         ``ExceptionInfo``) which makes Python keep all objects referenced
         from that cycle (including all local variables in the current
         frame) alive until the next cyclic garbage collection run. See the
         official Python ``try`` statement documentation for more detailed
         information.
 
     """
     __tracebackhide__ = True
-    msg = ("exceptions must be old-style classes or"
-           " derived from BaseException, not %s")
-    if isinstance(expected_exception, tuple):
-        for exc in expected_exception:
-            if not isclass(exc):
-                raise TypeError(msg % type(exc))
-    elif not isclass(expected_exception):
-        raise TypeError(msg % type(expected_exception))
+    for exc in filterfalse(isclass, always_iterable(expected_exception, BASE_TYPE)):
+        msg = (
+            "exceptions must be old-style classes or"
+            " derived from BaseException, not %s"
+        )
+        raise TypeError(msg % type(exc))
 
-    message = "DID NOT RAISE {0}".format(expected_exception)
+    message = "DID NOT RAISE {}".format(expected_exception)
     match_expr = None
 
     if not args:
         if "message" in kwargs:
             message = kwargs.pop("message")
         if "match" in kwargs:
             match_expr = kwargs.pop("match")
-            message += " matching '{0}'".format(match_expr)
+        if kwargs:
+            msg = "Unexpected keyword arguments passed to pytest.raises: "
+            msg += ", ".join(kwargs.keys())
+            raise TypeError(msg)
         return RaisesContext(expected_exception, message, match_expr)
     elif isinstance(args[0], str):
         code, = args
         assert isinstance(code, str)
         frame = sys._getframe(1)
         loc = frame.f_locals.copy()
         loc.update(kwargs)
         # print "raises frame scope: %r" % frame.f_locals
@@ -591,16 +645,17 @@ def raises(expected_exception, *args, **
             return _pytest._code.ExceptionInfo()
     fail(message)
 
 
 raises.Exception = fail.Exception
 
 
 class RaisesContext(object):
+
     def __init__(self, expected_exception, message, match_expr):
         self.expected_exception = expected_exception
         self.message = message
         self.match_expr = match_expr
         self.excinfo = None
 
     def __enter__(self):
         self.excinfo = object.__new__(_pytest._code.ExceptionInfo)
@@ -609,11 +664,11 @@ class RaisesContext(object):
     def __exit__(self, *tp):
         __tracebackhide__ = True
         if tp[0] is None:
             fail(self.message)
         self.excinfo.__init__(tp)
         suppress_exception = issubclass(self.excinfo.type, self.expected_exception)
         if sys.version_info[0] == 2 and suppress_exception:
             sys.exc_clear()
-        if self.match_expr:
+        if self.match_expr and suppress_exception:
             self.excinfo.match(self.match_expr)
         return suppress_exception
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/recwarn.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/recwarn.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/recwarn.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/recwarn.py
@@ -11,27 +11,24 @@ import warnings
 import re
 
 from _pytest.fixtures import yield_fixture
 from _pytest.outcomes import fail
 
 
 @yield_fixture
 def recwarn():
-    """Return a WarningsRecorder instance that provides these methods:
-
-    * ``pop(category=None)``: return last warning matching the category.
-    * ``clear()``: clear list of warnings
+    """Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.
 
     See http://docs.python.org/library/warnings.html for information
     on warning categories.
     """
     wrec = WarningsRecorder()
     with wrec:
-        warnings.simplefilter('default')
+        warnings.simplefilter("default")
         yield wrec
 
 
 def deprecated_call(func=None, *args, **kwargs):
     """context manager that can be used to ensure a block of code triggers a
     ``DeprecationWarning`` or ``PendingDeprecationWarning``::
 
         >>> import warnings
@@ -74,30 +71,32 @@ class _DeprecatedCallContext(object):
             self._captured_categories.append(category)
 
     def __exit__(self, exc_type, exc_val, exc_tb):
         warnings.warn_explicit = self._old_warn_explicit
         warnings.warn = self._old_warn
 
         if exc_type is None:
             deprecation_categories = (DeprecationWarning, PendingDeprecationWarning)
-            if not any(issubclass(c, deprecation_categories) for c in self._captured_categories):
+            if not any(
+                issubclass(c, deprecation_categories) for c in self._captured_categories
+            ):
                 __tracebackhide__ = True
                 msg = "Did not produce DeprecationWarning or PendingDeprecationWarning"
                 raise AssertionError(msg)
 
 
 def warns(expected_warning, *args, **kwargs):
-    """Assert that code raises a particular class of warning.
+    r"""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).
+    Specifically, the parameter ``expected_warning`` can be a warning class or
+    sequence of warning classes, and the inside the ``with`` block must issue a warning of that class or
+    classes.
 
-    This helper produces a list of ``warnings.WarningMessage`` objects,
+    This helper produces a list of :class:`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)
 
@@ -178,32 +177,34 @@ class WarningsRecorder(warnings.catch_wa
         """Clear the list of recorded warnings."""
         self._list[:] = []
 
     def __enter__(self):
         if self._entered:
             __tracebackhide__ = True
             raise RuntimeError("Cannot enter %r twice" % self)
         self._list = super(WarningsRecorder, self).__enter__()
-        warnings.simplefilter('always')
+        warnings.simplefilter("always")
         return self
 
     def __exit__(self, *exc_info):
         if not self._entered:
             __tracebackhide__ = True
             raise RuntimeError("Cannot exit %r without entering first" % self)
         super(WarningsRecorder, self).__exit__(*exc_info)
 
 
 class WarningsChecker(WarningsRecorder):
+
     def __init__(self, expected_warning=None, match_expr=None):
         super(WarningsChecker, self).__init__()
 
-        msg = ("exceptions must be old-style classes or "
-               "derived from Warning, not %s")
+        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))
@@ -212,25 +213,31 @@ class WarningsChecker(WarningsRecorder):
         self.match_expr = match_expr
 
     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(issubclass(r.category, self.expected_warning)
-                           for r in self):
+                if not any(issubclass(r.category, self.expected_warning) for r in self):
                     __tracebackhide__ = True
-                    fail("DID NOT WARN. No warnings of type {0} was emitted. "
-                         "The list of emitted warnings is: {1}.".format(
-                             self.expected_warning,
-                             [each.message for each in self]))
+                    fail(
+                        "DID NOT WARN. No warnings of type {} was emitted. "
+                        "The list of emitted warnings is: {}.".format(
+                            self.expected_warning, [each.message for each in self]
+                        )
+                    )
                 elif self.match_expr is not None:
                     for r in self:
                         if issubclass(r.category, self.expected_warning):
                             if re.compile(self.match_expr).search(str(r.message)):
                                 break
                     else:
-                        fail("DID NOT WARN. No warnings of type {0} matching"
-                             " ('{1}') was emitted. The list of emitted warnings"
-                             " is: {2}.".format(self.expected_warning, self.match_expr,
-                                                [each.message for each in self]))
+                        fail(
+                            "DID NOT WARN. No warnings of type {} matching"
+                            " ('{}') was emitted. The list of emitted warnings"
+                            " is: {}.".format(
+                                self.expected_warning,
+                                self.match_expr,
+                                [each.message for each in self],
+                            )
+                        )
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/resultlog.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/resultlog.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/resultlog.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/resultlog.py
@@ -4,93 +4,100 @@ text file.
 from __future__ import absolute_import, division, print_function
 
 import py
 import os
 
 
 def pytest_addoption(parser):
     group = parser.getgroup("terminal reporting", "resultlog plugin options")
-    group.addoption('--resultlog', '--result-log', action="store",
-                    metavar="path", default=None,
-                    help="DEPRECATED path for machine-readable result log.")
+    group.addoption(
+        "--resultlog",
+        "--result-log",
+        action="store",
+        metavar="path",
+        default=None,
+        help="DEPRECATED path for machine-readable result log.",
+    )
 
 
 def pytest_configure(config):
     resultlog = config.option.resultlog
     # prevent opening resultlog on slave nodes (xdist)
-    if resultlog and not hasattr(config, 'slaveinput'):
+    if resultlog and not hasattr(config, "slaveinput"):
         dirname = os.path.dirname(os.path.abspath(resultlog))
         if not os.path.isdir(dirname):
             os.makedirs(dirname)
-        logfile = open(resultlog, 'w', 1)  # line buffered
+        logfile = open(resultlog, "w", 1)  # line buffered
         config._resultlog = ResultLog(config, logfile)
         config.pluginmanager.register(config._resultlog)
 
         from _pytest.deprecated import RESULT_LOG
-        config.warn('C1', RESULT_LOG)
+
+        config.warn("C1", RESULT_LOG)
 
 
 def pytest_unconfigure(config):
-    resultlog = getattr(config, '_resultlog', None)
+    resultlog = getattr(config, "_resultlog", None)
     if resultlog:
         resultlog.logfile.close()
         del config._resultlog
         config.pluginmanager.unregister(resultlog)
 
 
 def generic_path(item):
     chain = item.listchain()
     gpath = [chain[0].name]
     fspath = chain[0].fspath
     fspart = False
     for node in chain[1:]:
         newfspath = node.fspath
         if newfspath == fspath:
             if fspart:
-                gpath.append(':')
+                gpath.append(":")
                 fspart = False
             else:
-                gpath.append('.')
+                gpath.append(".")
         else:
-            gpath.append('/')
+            gpath.append("/")
             fspart = True
         name = node.name
-        if name[0] in '([':
+        if name[0] in "([":
             gpath.pop()
         gpath.append(name)
         fspath = newfspath
-    return ''.join(gpath)
+    return "".join(gpath)
 
 
 class ResultLog(object):
+
     def __init__(self, config, logfile):
         self.config = config
         self.logfile = logfile  # preferably line buffered
 
     def write_log_entry(self, testpath, lettercode, longrepr):
         print("%s %s" % (lettercode, testpath), file=self.logfile)
         for line in longrepr.splitlines():
             print(" %s" % line, file=self.logfile)
 
     def log_outcome(self, report, lettercode, longrepr):
-        testpath = getattr(report, 'nodeid', None)
+        testpath = getattr(report, "nodeid", None)
         if testpath is None:
             testpath = report.fspath
         self.write_log_entry(testpath, lettercode, longrepr)
 
     def pytest_runtest_logreport(self, report):
         if report.when != "call" and report.passed:
             return
         res = self.config.hook.pytest_report_teststatus(report=report)
         code = res[1]
-        if code == 'x':
+        if code == "x":
             longrepr = str(report.longrepr)
-        elif code == 'X':
-            longrepr = ''
+        elif code == "X":
+            longrepr = ""
         elif report.passed:
             longrepr = ""
         elif report.failed:
             longrepr = str(report.longrepr)
         elif report.skipped:
             longrepr = str(report.longrepr[2])
         self.log_outcome(report, code, longrepr)
 
@@ -101,13 +108,13 @@ class ResultLog(object):
                 longrepr = str(report.longrepr)
             else:
                 assert report.skipped
                 code = "S"
                 longrepr = "%s:%d: %s" % report.longrepr
             self.log_outcome(report, code, longrepr)
 
     def pytest_internalerror(self, excrepr):
-        reprcrash = getattr(excrepr, 'reprcrash', None)
+        reprcrash = getattr(excrepr, "reprcrash", None)
         path = getattr(reprcrash, "path", None)
         if path is None:
             path = "cwd:%s" % py.path.local()
-        self.write_log_entry(path, '!', str(excrepr))
+        self.write_log_entry(path, "!", str(excrepr))
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/runner.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/runner.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/runner.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/runner.py
@@ -11,132 +11,135 @@ from _pytest._code.code import TerminalR
 from _pytest.outcomes import skip, Skipped, TEST_OUTCOME
 
 #
 # pytest plugin hooks
 
 
 def pytest_addoption(parser):
     group = parser.getgroup("terminal reporting", "reporting", after="general")
-    group.addoption('--durations',
-                    action="store", type=int, default=None, metavar="N",
-                    help="show N slowest setup/test durations (N=0 for all)."),
+    group.addoption(
+        "--durations",
+        action="store",
+        type=int,
+        default=None,
+        metavar="N",
+        help="show N slowest setup/test durations (N=0 for all).",
+    ),
 
 
 def pytest_terminal_summary(terminalreporter):
     durations = terminalreporter.config.option.durations
     if durations is None:
         return
     tr = terminalreporter
     dlist = []
     for replist in tr.stats.values():
         for rep in replist:
-            if hasattr(rep, 'duration'):
+            if hasattr(rep, "duration"):
                 dlist.append(rep)
     if not dlist:
         return
     dlist.sort(key=lambda x: x.duration)
     dlist.reverse()
     if not durations:
         tr.write_sep("=", "slowest test durations")
     else:
         tr.write_sep("=", "slowest %s test durations" % durations)
         dlist = dlist[:durations]
 
     for rep in dlist:
         nodeid = rep.nodeid.replace("::()::", "::")
-        tr.write_line("%02.2fs %-8s %s" %
-                      (rep.duration, rep.when, nodeid))
+        tr.write_line("%02.2fs %-8s %s" % (rep.duration, rep.when, nodeid))
 
 
 def pytest_sessionstart(session):
     session._setupstate = SetupState()
 
 
 def pytest_sessionfinish(session):
     session._setupstate.teardown_all()
 
 
 def pytest_runtest_protocol(item, nextitem):
-    item.ihook.pytest_runtest_logstart(
-        nodeid=item.nodeid, location=item.location,
-    )
+    item.ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location)
     runtestprotocol(item, nextitem=nextitem)
+    item.ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)
     return True
 
 
 def runtestprotocol(item, log=True, nextitem=None):
     hasrequest = hasattr(item, "_request")
     if hasrequest and not item._request:
         item._initrequest()
     rep = call_and_report(item, "setup", log)
     reports = [rep]
     if rep.passed:
         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))
+    reports.append(call_and_report(item, "teardown", log, nextitem=nextitem))
     # after all teardown hooks have been called
     # want funcargs and request info to go away
     if hasrequest:
         item._request = False
         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(" " * 8)
     tw.write(item._nodeid)
     used_fixtures = sorted(item._fixtureinfo.name2fixturedefs.keys())
     if used_fixtures:
-        tw.write(' (fixtures used: {0})'.format(', '.join(used_fixtures)))
+        tw.write(" (fixtures used: {})".format(", ".join(used_fixtures)))
 
 
 def pytest_runtest_setup(item):
-    _update_current_test_var(item, 'setup')
+    _update_current_test_var(item, "setup")
     item.session._setupstate.prepare(item)
 
 
 def pytest_runtest_call(item):
-    _update_current_test_var(item, 'call')
+    _update_current_test_var(item, "call")
+    sys.last_type, sys.last_value, sys.last_traceback = (None, None, None)
     try:
         item.runtest()
     except Exception:
         # Store trace info to allow postmortem debugging
         type, value, tb = sys.exc_info()
         tb = tb.tb_next  # Skip *this* frame
         sys.last_type = type
         sys.last_value = value
         sys.last_traceback = tb
-        del tb  # Get rid of it in this namespace
+        del type, value, tb  # Get rid of these in this frame
         raise
 
 
 def pytest_runtest_teardown(item, nextitem):
-    _update_current_test_var(item, 'teardown')
+    _update_current_test_var(item, "teardown")
     item.session._setupstate.teardown_exact(item, nextitem)
     _update_current_test_var(item, None)
 
 
 def _update_current_test_var(item, when):
     """
     Update PYTEST_CURRENT_TEST to reflect the current item and stage.
 
     If ``when`` is None, delete PYTEST_CURRENT_TEST from the environment.
     """
-    var_name = 'PYTEST_CURRENT_TEST'
+    var_name = "PYTEST_CURRENT_TEST"
     if when:
-        value = '{0} ({1})'.format(item.nodeid, when)
+        value = "{} ({})".format(item.nodeid, when)
         # don't allow null bytes on environment variables (see #2644, #2957)
-        value = value.replace('\x00', '(null)')
+        value = value.replace("\x00", "(null)")
         os.environ[var_name] = value
     else:
         os.environ.pop(var_name)
 
 
 def pytest_report_teststatus(report):
     if report.when in ("setup", "teardown"):
         if report.failed:
@@ -146,55 +149,64 @@ def pytest_report_teststatus(report):
             return "skipped", "s", "SKIPPED"
         else:
             return "", "", ""
 
 
 #
 # Implementation
 
+
 def call_and_report(item, when, log=True, **kwds):
     call = call_runtest_hook(item, when, **kwds)
     hook = item.ihook
     report = hook.pytest_runtest_makereport(item=item, call=call)
     if log:
         hook.pytest_runtest_logreport(report=report)
     if check_interactive_exception(call, report):
         hook.pytest_exception_interact(node=item, call=call, report=report)
     return report
 
 
 def check_interactive_exception(call, report):
     return call.excinfo and not (
-        hasattr(report, "wasxfail") or
-        call.excinfo.errisinstance(skip.Exception) or
-        call.excinfo.errisinstance(bdb.BdbQuit))
+        hasattr(report, "wasxfail")
+        or call.excinfo.errisinstance(skip.Exception)
+        or call.excinfo.errisinstance(bdb.BdbQuit)
+    )
 
 
 def call_runtest_hook(item, when, **kwds):
     hookname = "pytest_runtest_" + when
     ihook = getattr(item.ihook, hookname)
-    return CallInfo(lambda: ihook(item=item, **kwds), when=when)
+    return CallInfo(
+        lambda: ihook(item=item, **kwds),
+        when=when,
+        treat_keyboard_interrupt_as_exception=item.config.getvalue("usepdb"),
+    )
 
 
-class CallInfo:
+class CallInfo(object):
     """ Result/Exception info a function invocation. """
     #: None or ExceptionInfo object.
     excinfo = None
 
-    def __init__(self, func, when):
+    def __init__(self, func, when, treat_keyboard_interrupt_as_exception=False):
         #: context of invocation: one of "setup", "call",
         #: "teardown", "memocollect"
         self.when = when
         self.start = time()
         try:
             self.result = func()
         except KeyboardInterrupt:
-            self.stop = time()
-            raise
+            if treat_keyboard_interrupt_as_exception:
+                self.excinfo = ExceptionInfo()
+            else:
+                self.stop = time()
+                raise
         except:  # noqa
             self.excinfo = ExceptionInfo()
         self.stop = time()
 
     def __repr__(self):
         if self.excinfo:
             status = "exception: %s" % str(self.excinfo.value)
         else:
@@ -202,36 +214,37 @@ class CallInfo:
         return "<CallInfo when=%r %s>" % (self.when, status)
 
 
 def getslaveinfoline(node):
     try:
         return node._slaveinfocache
     except AttributeError:
         d = node.slaveinfo
-        ver = "%s.%s.%s" % d['version_info'][:3]
+        ver = "%s.%s.%s" % d["version_info"][:3]
         node._slaveinfocache = s = "[%s] %s -- Python %s %s" % (
-            d['id'], d['sysplatform'], ver, d['executable'])
+            d["id"], d["sysplatform"], ver, d["executable"]
+        )
         return s
 
 
 class BaseReport(object):
 
     def __init__(self, **kw):
         self.__dict__.update(kw)
 
     def toterminal(self, out):
-        if hasattr(self, 'node'):
+        if hasattr(self, "node"):
             out.line(getslaveinfoline(self.node))
 
         longrepr = self.longrepr
         if longrepr is None:
             return
 
-        if hasattr(longrepr, 'toterminal'):
+        if hasattr(longrepr, "toterminal"):
             longrepr.toterminal(out)
         else:
             try:
                 out.line(longrepr)
             except UnicodeEncodeError:
                 out.line("<unprintable longrepr>")
 
     def get_sections(self, prefix):
@@ -249,44 +262,58 @@ class BaseReport(object):
         """
         tw = py.io.TerminalWriter(stringio=True)
         tw.hasmarkup = False
         self.toterminal(tw)
         exc = tw.stringio.getvalue()
         return exc.strip()
 
     @property
+    def caplog(self):
+        """Return captured log lines, if log capturing is enabled
+
+        .. versionadded:: 3.5
+        """
+        return "\n".join(
+            content for (prefix, content) in self.get_sections("Captured log")
+        )
+
+    @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'))
+        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'))
+        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")
 
     @property
     def fspath(self):
         return self.nodeid.split("::")[0]
 
 
 def pytest_runtest_makereport(item, call):
     when = call.when
     duration = call.stop - call.start
-    keywords = dict([(x, 1) for x in item.keywords])
+    keywords = {x: 1 for x in item.keywords}
     excinfo = call.excinfo
     sections = []
     if not call.excinfo:
         outcome = "passed"
         longrepr = None
     else:
         if not isinstance(excinfo, ExceptionInfo):
             outcome = "failed"
@@ -295,32 +322,52 @@ def pytest_runtest_makereport(item, call
             outcome = "skipped"
             r = excinfo._getreprcrash()
             longrepr = (str(r.path), r.lineno, r.message)
         else:
             outcome = "failed"
             if call.when == "call":
                 longrepr = item.repr_failure(excinfo)
             else:  # exception in setup or teardown
-                longrepr = item._repr_failure_py(excinfo,
-                                                 style=item.config.option.tbstyle)
+                longrepr = item._repr_failure_py(
+                    excinfo, style=item.config.option.tbstyle
+                )
     for rwhen, key, content in item._report_sections:
         sections.append(("Captured %s %s" % (key, rwhen), content))
-    return TestReport(item.nodeid, item.location,
-                      keywords, outcome, longrepr, when,
-                      sections, duration)
+    return TestReport(
+        item.nodeid,
+        item.location,
+        keywords,
+        outcome,
+        longrepr,
+        when,
+        sections,
+        duration,
+        user_properties=item.user_properties,
+    )
 
 
 class TestReport(BaseReport):
     """ Basic test report object (also used for setup and teardown calls if
     they fail).
     """
 
-    def __init__(self, nodeid, location, keywords, outcome,
-                 longrepr, when, sections=(), duration=0, **extra):
+    def __init__(
+        self,
+        nodeid,
+        location,
+        keywords,
+        outcome,
+        longrepr,
+        when,
+        sections=(),
+        duration=0,
+        user_properties=(),
+        **extra
+    ):
         #: normalized collection node id
         self.nodeid = nodeid
 
         #: a (filesystempath, lineno, domaininfo) tuple indicating the
         #: actual location of a test item - it might be different from the
         #: collected one e.g. if a method is inherited from a different module.
         self.location = location
 
@@ -332,88 +379,95 @@ class TestReport(BaseReport):
         self.outcome = outcome
 
         #: None or a failure representation.
         self.longrepr = longrepr
 
         #: one of 'setup', 'call', 'teardown' to indicate runtest phase.
         self.when = when
 
+        #: user properties is a list of tuples (name, value) that holds user
+        #: defined properties of the test
+        self.user_properties = user_properties
+
         #: 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
         self.duration = duration
 
         self.__dict__.update(extra)
 
     def __repr__(self):
         return "<TestReport %r when=%r outcome=%r>" % (
-            self.nodeid, self.when, self.outcome)
+            self.nodeid, self.when, self.outcome
+        )
 
 
 class TeardownErrorReport(BaseReport):
     outcome = "failed"
     when = "teardown"
 
     def __init__(self, longrepr, **extra):
         self.longrepr = longrepr
         self.sections = []
         self.__dict__.update(extra)
 
 
 def pytest_make_collect_report(collector):
-    call = CallInfo(
-        lambda: list(collector.collect()),
-        'collect')
+    call = CallInfo(lambda: list(collector.collect()), "collect")
     longrepr = None
     if not call.excinfo:
         outcome = "passed"
     else:
         from _pytest import nose
+
         skip_exceptions = (Skipped,) + nose.get_skip_exceptions()
         if call.excinfo.errisinstance(skip_exceptions):
             outcome = "skipped"
             r = collector._repr_failure_py(call.excinfo, "line").reprcrash
             longrepr = (str(r.path), r.lineno, r.message)
         else:
             outcome = "failed"
             errorinfo = collector.repr_failure(call.excinfo)
             if not hasattr(errorinfo, "toterminal"):
                 errorinfo = CollectErrorRepr(errorinfo)
             longrepr = errorinfo
-    rep = CollectReport(collector.nodeid, outcome, longrepr,
-                        getattr(call, 'result', None))
+    rep = CollectReport(
+        collector.nodeid, outcome, longrepr, getattr(call, "result", None)
+    )
     rep.call = call  # see collect_one_node
     return rep
 
 
 class CollectReport(BaseReport):
-    def __init__(self, nodeid, outcome, longrepr, result,
-                 sections=(), **extra):
+
+    def __init__(self, nodeid, outcome, longrepr, result, sections=(), **extra):
         self.nodeid = nodeid
         self.outcome = outcome
         self.longrepr = longrepr
         self.result = result or []
         self.sections = list(sections)
         self.__dict__.update(extra)
 
     @property
     def location(self):
         return (self.fspath, None, self.fspath)
 
     def __repr__(self):
         return "<CollectReport %r lenresult=%s outcome=%r>" % (
-            self.nodeid, len(self.result), self.outcome)
+            self.nodeid, len(self.result), self.outcome
+        )
 
 
 class CollectErrorRepr(TerminalRepr):
+
     def __init__(self, msg):
         self.longrepr = msg
 
     def toterminal(self, out):
         out.line(self.longrepr, red=True)
 
 
 class SetupState(object):
@@ -452,45 +506,55 @@ class SetupState(object):
         if exc:
             py.builtin._reraise(*exc)
 
     def _teardown_with_finalization(self, colitem):
         self._callfinalizers(colitem)
         if hasattr(colitem, "teardown"):
             colitem.teardown()
         for colitem in self._finalizers:
-            assert colitem is None or colitem in self.stack \
-                or isinstance(colitem, tuple)
+            assert (
+                colitem is None or colitem in self.stack or isinstance(colitem, tuple)
+            )
 
     def teardown_all(self):
         while self.stack:
             self._pop_and_teardown()
         for key in list(self._finalizers):
             self._teardown_with_finalization(key)
         assert not self._finalizers
 
     def teardown_exact(self, item, nextitem):
         needed_collectors = nextitem and nextitem.listchain() or []
         self._teardown_towards(needed_collectors)
 
     def _teardown_towards(self, needed_collectors):
+        exc = None
         while self.stack:
             if self.stack == needed_collectors[:len(self.stack)]:
                 break
-            self._pop_and_teardown()
+            try:
+                self._pop_and_teardown()
+            except TEST_OUTCOME:
+                # XXX Only first exception will be seen by user,
+                #     ideally all should be reported.
+                if exc is None:
+                    exc = sys.exc_info()
+        if exc:
+            py.builtin._reraise(*exc)
 
     def prepare(self, colitem):
         """ setup objects along the collector chain to the test-method
             and teardown previously setup objects."""
         needed_collectors = colitem.listchain()
         self._teardown_towards(needed_collectors)
 
         # check if the last collection node has raised an error
         for col in self.stack:
-            if hasattr(col, '_prepare_exc'):
+            if hasattr(col, "_prepare_exc"):
                 py.builtin._reraise(*col._prepare_exc)
         for col in needed_collectors[len(self.stack):]:
             self.stack.append(col)
             try:
                 col.setup()
             except TEST_OUTCOME:
                 col._prepare_exc = sys.exc_info()
                 raise
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/setuponly.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/setuponly.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/setuponly.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/setuponly.py
@@ -1,71 +1,81 @@
 from __future__ import absolute_import, division, print_function
 
 import pytest
 import sys
 
 
 def pytest_addoption(parser):
     group = parser.getgroup("debugconfig")
-    group.addoption('--setuponly', '--setup-only', action="store_true",
-                    help="only setup fixtures, do not execute tests.")
-    group.addoption('--setupshow', '--setup-show', action="store_true",
-                    help="show setup of fixtures while executing tests.")
+    group.addoption(
+        "--setuponly",
+        "--setup-only",
+        action="store_true",
+        help="only setup fixtures, do not execute tests.",
+    )
+    group.addoption(
+        "--setupshow",
+        "--setup-show",
+        action="store_true",
+        help="show setup of fixtures while executing tests.",
+    )
 
 
 @pytest.hookimpl(hookwrapper=True)
 def pytest_fixture_setup(fixturedef, request):
     yield
     config = request.config
     if config.option.setupshow:
-        if hasattr(request, 'param'):
+        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]
+                    fixturedef.cached_param = fixturedef.ids[request.param_index]
             else:
                 fixturedef.cached_param = request.param
-        _show_fixture_action(fixturedef, 'SETUP')
+        _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')
+            _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')
+    capman = config.pluginmanager.getplugin("capturemanager")
     if capman:
         out, err = capman.suspend_global_capture()
 
     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))
+    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 msg == "SETUP":
+        deps = sorted(arg for arg in fixturedef.argnames if arg != "request")
         if deps:
-            tw.write(' (fixtures used: {0})'.format(', '.join(deps)))
+            tw.write(" (fixtures used: {})".format(", ".join(deps)))
 
-    if hasattr(fixturedef, 'cached_param'):
-        tw.write('[{0}]'.format(fixturedef.cached_param))
+    if hasattr(fixturedef, "cached_param"):
+        tw.write("[{}]".format(fixturedef.cached_param))
 
     if capman:
         capman.resume_global_capture()
         sys.stdout.write(out)
         sys.stderr.write(err)
 
 
 @pytest.hookimpl(tryfirst=True)
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/setupplan.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/setupplan.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/setupplan.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/setupplan.py
@@ -1,18 +1,22 @@
 from __future__ import absolute_import, division, print_function
 
 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.")
+    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
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/skipping.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/skipping.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/skipping.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/skipping.py
@@ -1,198 +1,94 @@
 """ support for skip/xfail functions and markers. """
 from __future__ import absolute_import, division, print_function
 
-import os
-import six
-import sys
-import traceback
-
 from _pytest.config import hookimpl
-from _pytest.mark import MarkInfo, MarkDecorator
-from _pytest.outcomes import fail, skip, xfail, TEST_OUTCOME
+from _pytest.mark.evaluate import MarkEvaluator
+from _pytest.outcomes import fail, skip, xfail
 
 
 def pytest_addoption(parser):
     group = parser.getgroup("general")
-    group.addoption('--runxfail',
-                    action="store_true", dest="runxfail", default=False,
-                    help="run tests even if they are marked xfail")
+    group.addoption(
+        "--runxfail",
+        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")
+    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:
         # yay a hack
         import pytest
+
         old = pytest.xfail
         config._cleanup.append(lambda: setattr(pytest, "xfail", old))
 
         def nop(*args, **kwargs):
             pass
 
         nop.Exception = xfail.Exception
         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 "
-                            "module global context. Example: skipif('sys.platform == \"win32\"') "
-                            "skips the test if we are on the win32 platform. see "
-                            "http://pytest.org/latest/skipping.html"
-                            )
-    config.addinivalue_line("markers",
-                            "xfail(condition, reason=None, run=True, raises=None, strict=False): "
-                            "mark 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"
-                            )
-
-
-class MarkEvaluator(object):
-    def __init__(self, item, name):
-        self.item = item
-        self._marks = None
-        self._mark = None
-        self._mark_name = name
-
-    def __bool__(self):
-        self._marks = self._get_marks()
-        return bool(self._marks)
-    __nonzero__ = __bool__
-
-    def wasvalid(self):
-        return not hasattr(self, 'exc')
-
-    def _get_marks(self):
-
-        keyword = self.item.keywords.get(self._mark_name)
-        if isinstance(keyword, MarkDecorator):
-            return [keyword.mark]
-        elif isinstance(keyword, MarkInfo):
-            return [x.combined for x in keyword]
-        else:
-            return []
-
-    def invalidraise(self, exc):
-        raises = self.get('raises')
-        if not raises:
-            return
-        return not isinstance(exc, raises)
-
-    def istrue(self):
-        try:
-            return self._istrue()
-        except TEST_OUTCOME:
-            self.exc = sys.exc_info()
-            if isinstance(self.exc[1], SyntaxError):
-                msg = [" " * (self.exc[1].offset + 4) + "^", ]
-                msg.append("SyntaxError: invalid syntax")
-            else:
-                msg = traceback.format_exception_only(*self.exc[:2])
-            fail("Error evaluating %r expression\n"
-                 "    %s\n"
-                 "%s"
-                 % (self._mark_name, self.expr, "\n".join(msg)),
-                 pytrace=False)
-
-    def _getglobals(self):
-        d = {'os': os, 'sys': sys, 'config': self.item.config}
-        if hasattr(self.item, 'obj'):
-            d.update(self.item.obj.__globals__)
-        return d
-
-    def _istrue(self):
-        if hasattr(self, 'result'):
-            return self.result
-        self._marks = self._get_marks()
-
-        if self._marks:
-            self.result = False
-            for mark in self._marks:
-                self._mark = mark
-                if 'condition' in mark.kwargs:
-                    args = (mark.kwargs['condition'],)
-                else:
-                    args = mark.args
-
-                for expr in args:
-                    self.expr = expr
-                    if isinstance(expr, six.string_types):
-                        d = self._getglobals()
-                        result = cached_eval(self.item.config, expr, d)
-                    else:
-                        if "reason" not in mark.kwargs:
-                            # XXX better be checked at collection time
-                            msg = "you need to specify reason=STRING " \
-                                  "when using booleans as conditions."
-                            fail(msg)
-                        result = bool(expr)
-                    if result:
-                        self.result = True
-                        self.reason = mark.kwargs.get('reason', None)
-                        self.expr = expr
-                        return self.result
-
-                if not args:
-                    self.result = True
-                    self.reason = mark.kwargs.get('reason', None)
-                    return self.result
-        return False
-
-    def get(self, attr, default=None):
-        if self._mark is None:
-            return default
-        return self._mark.kwargs.get(attr, default)
-
-    def getexplanation(self):
-        expl = getattr(self, 'reason', None) or self.get('reason', None)
-        if not expl:
-            if not hasattr(self, 'expr'):
-                return ""
-            else:
-                return "condition: " + str(self.expr)
-        return expl
+    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 "
+        "module global context. Example: skipif('sys.platform == \"win32\"') "
+        "skips the test if we are on the win32 platform. see "
+        "http://pytest.org/latest/skipping.html",
+    )
+    config.addinivalue_line(
+        "markers",
+        "xfail(condition, reason=None, run=True, raises=None, strict=False): "
+        "mark 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",
+    )
 
 
 @hookimpl(tryfirst=True)
 def pytest_runtest_setup(item):
     # Check if skip or skipif are specified as pytest marks
     item._skipped_by_mark = False
-    skipif_info = item.keywords.get('skipif')
-    if isinstance(skipif_info, (MarkInfo, MarkDecorator)):
-        eval_skipif = MarkEvaluator(item, 'skipif')
-        if eval_skipif.istrue():
-            item._skipped_by_mark = True
-            skip(eval_skipif.getexplanation())
+    eval_skipif = MarkEvaluator(item, "skipif")
+    if eval_skipif.istrue():
+        item._skipped_by_mark = True
+        skip(eval_skipif.getexplanation())
 
-    skip_info = item.keywords.get('skip')
-    if isinstance(skip_info, (MarkInfo, MarkDecorator)):
+    for skip_info in item.iter_markers(name="skip"):
         item._skipped_by_mark = True
-        if 'reason' in skip_info.kwargs:
-            skip(skip_info.kwargs['reason'])
+        if "reason" in skip_info.kwargs:
+            skip(skip_info.kwargs["reason"])
         elif skip_info.args:
             skip(skip_info.args[0])
         else:
             skip("unconditional skip")
 
-    item._evalxfail = MarkEvaluator(item, 'xfail')
+    item._evalxfail = MarkEvaluator(item, "xfail")
     check_xfail_no_run(item)
 
 
 @hookimpl(hookwrapper=True)
 def pytest_pyfunc_call(pyfuncitem):
     check_xfail_no_run(pyfuncitem)
     outcome = yield
     passed = outcome.excinfo is None
@@ -200,117 +96,111 @@ def pytest_pyfunc_call(pyfuncitem):
         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):
+            if not evalxfail.get("run", True):
                 xfail("[NOTRUN] " + evalxfail.getexplanation())
 
 
 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)
+        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()
-            fail('[XPASS(strict)] ' + explanation, pytrace=False)
+            fail("[XPASS(strict)] " + explanation, pytrace=False)
 
 
 @hookimpl(hookwrapper=True)
 def pytest_runtest_makereport(item, call):
     outcome = yield
     rep = outcome.get_result()
-    evalxfail = getattr(item, '_evalxfail', None)
+    evalxfail = getattr(item, "_evalxfail", None)
     # unitttest special case, see setting of _unexpectedsuccess
-    if hasattr(item, '_unexpectedsuccess') and rep.when == "call":
+    if hasattr(item, "_unexpectedsuccess") and rep.when == "call":
         from _pytest.compat import _is_unittest_unexpected_success_a_failure
+
         if item._unexpectedsuccess:
-            rep.longrepr = "Unexpected success: {0}".format(item._unexpectedsuccess)
+            rep.longrepr = "Unexpected success: {}".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
+        pass  # don't interefere
     elif call.excinfo and call.excinfo.errisinstance(xfail.Exception):
         rep.wasxfail = "reason: " + call.excinfo.value.msg
         rep.outcome = "skipped"
-    elif evalxfail and not rep.skipped and evalxfail.wasvalid() and \
-            evalxfail.istrue():
+    elif evalxfail and not rep.skipped and evalxfail.wasvalid() and evalxfail.istrue():
         if call.excinfo:
             if evalxfail.invalidraise(call.excinfo.value):
                 rep.outcome = "failed"
             else:
                 rep.outcome = "skipped"
                 rep.wasxfail = evalxfail.getexplanation()
         elif call.when == "call":
-            strict_default = item.config.getini('xfail_strict')
-            is_strict_xfail = evalxfail.get('strict', strict_default)
+            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)
+                rep.longrepr = "[XPASS(strict)] {}".format(explanation)
             else:
                 rep.outcome = "passed"
                 rep.wasxfail = explanation
-    elif item._skipped_by_mark and rep.skipped and type(rep.longrepr) is tuple:
+    elif getattr(item, "_skipped_by_mark", False) 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
         # the location of where the skip exception was raised within pytest
         filename, line, reason = rep.longrepr
         filename, line = item.location[:2]
         rep.longrepr = filename, line, reason
 
+
 # called by terminalreporter progress reporting
 
 
 def pytest_report_teststatus(report):
     if hasattr(report, "wasxfail"):
         if report.skipped:
             return "xfailed", "x", "xfail"
         elif report.passed:
-            return "xpassed", "X", ("XPASS", {'yellow': True})
+            return "xpassed", "X", ("XPASS", {"yellow": True})
+
 
 # called by the terminalreporter instance/plugin
 
 
 def pytest_terminal_summary(terminalreporter):
     tr = terminalreporter
     if not tr.reportchars:
         # for name in "xfailed skipped failed xpassed":
         #    if not tr.stats.get(name, 0):
         #        tr.write_line("HINT: use '-r' option to see extra "
         #              "summary info about tests")
         #        break
         return
 
     lines = []
     for char in tr.reportchars:
-        if char == "x":
-            show_xfailed(terminalreporter, lines)
-        elif char == "X":
-            show_xpassed(terminalreporter, lines)
-        elif char in "fF":
-            show_simple(terminalreporter, lines, 'failed', "FAIL %s")
-        elif char in "sS":
-            show_skipped(terminalreporter, lines)
-        elif char == "E":
-            show_simple(terminalreporter, lines, 'error', "ERROR %s")
-        elif char == 'p':
-            show_simple(terminalreporter, lines, 'passed', "PASSED %s")
+        action = REPORTCHAR_ACTIONS.get(char, lambda tr, lines: None)
+        action(terminalreporter, lines)
 
     if lines:
         tr._tw.sep("=", "short test summary info")
         for line in lines:
             tr._tw.line(line)
 
 
 def show_simple(terminalreporter, lines, stat, format):
@@ -336,62 +226,68 @@ def show_xpassed(terminalreporter, lines
     xpassed = terminalreporter.stats.get("xpassed")
     if xpassed:
         for rep in xpassed:
             pos = terminalreporter.config.cwd_relative_nodeid(rep.nodeid)
             reason = rep.wasxfail
             lines.append("XPASS %s %s" % (pos, reason))
 
 
-def cached_eval(config, expr, d):
-    if not hasattr(config, '_evalcache'):
-        config._evalcache = {}
-    try:
-        return config._evalcache[expr]
-    except KeyError:
-        import _pytest._code
-        exprcode = _pytest._code.compile(expr, mode="eval")
-        config._evalcache[expr] = x = eval(exprcode, d)
-        return x
-
-
 def folded_skips(skipped):
     d = {}
     for event in skipped:
         key = event.longrepr
         assert len(key) == 3, (event, key)
-        keywords = getattr(event, 'keywords', {})
+        keywords = getattr(event, "keywords", {})
         # folding reports with global pytestmark variable
         # this is workaround, because for now we cannot identify the scope of a skip marker
         # TODO: revisit after marks scope would be fixed
-        when = getattr(event, 'when', None)
-        if when == 'setup' and 'skip' in keywords and 'pytestmark' not in keywords:
-            key = (key[0], None, key[2], )
+        when = getattr(event, "when", None)
+        if when == "setup" and "skip" in keywords and "pytestmark" not in keywords:
+            key = (key[0], None, key[2])
         d.setdefault(key, []).append(event)
     values = []
     for key, events in d.items():
         values.append((len(events),) + key)
     return values
 
 
 def show_skipped(terminalreporter, lines):
     tr = terminalreporter
-    skipped = tr.stats.get('skipped', [])
+    skipped = tr.stats.get("skipped", [])
     if skipped:
         # if not tr.hasopt('skipped'):
         #    tr.write_line(
         #        "%d skipped tests, specify -rs for more info" %
         #        len(skipped))
         #    return
         fskips = folded_skips(skipped)
         if fskips:
             # tr.write_sep("_", "skipped test summary")
             for num, fspath, lineno, reason in fskips:
                 if reason.startswith("Skipped: "):
                     reason = reason[9:]
                 if lineno is not None:
                     lines.append(
-                        "SKIP [%d] %s:%d: %s" %
-                        (num, fspath, lineno + 1, reason))
+                        "SKIP [%d] %s:%d: %s" % (num, fspath, lineno + 1, reason)
+                    )
                 else:
-                    lines.append(
-                        "SKIP [%d] %s: %s" %
-                        (num, fspath, reason))
+                    lines.append("SKIP [%d] %s: %s" % (num, fspath, reason))
+
+
+def shower(stat, format):
+
+    def show_(terminalreporter, lines):
+        return show_simple(terminalreporter, lines, stat, format)
+
+    return show_
+
+
+REPORTCHAR_ACTIONS = {
+    "x": show_xfailed,
+    "X": show_xpassed,
+    "f": shower("failed", "FAIL %s"),
+    "F": shower("failed", "FAIL %s"),
+    "s": show_skipped,
+    "S": show_skipped,
+    "p": shower("passed", "PASSED %s"),
+    "E": shower("error", "ERROR %s"),
+}
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/terminal.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/terminal.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/terminal.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/terminal.py
@@ -7,99 +7,189 @@ from __future__ import absolute_import, 
 import itertools
 import platform
 import sys
 import time
 
 import pluggy
 import py
 import six
+from more_itertools import collapse
 
 import pytest
 from _pytest import nodes
-from _pytest.main import EXIT_OK, EXIT_TESTSFAILED, EXIT_INTERRUPTED, \
-    EXIT_USAGEERROR, EXIT_NOTESTSCOLLECTED
+from _pytest.main import (
+    EXIT_OK,
+    EXIT_TESTSFAILED,
+    EXIT_INTERRUPTED,
+    EXIT_USAGEERROR,
+    EXIT_NOTESTSCOLLECTED,
+)
+
+
+import argparse
+
+
+class MoreQuietAction(argparse.Action):
+    """
+    a modified copy of the argparse count action which counts down and updates
+    the legacy quiet attribute at the same time
+
+    used to unify verbosity handling
+    """
+
+    def __init__(self, option_strings, dest, default=None, required=False, help=None):
+        super(MoreQuietAction, self).__init__(
+            option_strings=option_strings,
+            dest=dest,
+            nargs=0,
+            default=default,
+            required=required,
+            help=help,
+        )
+
+    def __call__(self, parser, namespace, values, option_string=None):
+        new_count = getattr(namespace, self.dest, 0) - 1
+        setattr(namespace, self.dest, new_count)
+        # todo Deprecate config.quiet
+        namespace.quiet = getattr(namespace, "quiet", 0) + 1
 
 
 def pytest_addoption(parser):
     group = parser.getgroup("terminal reporting", "reporting", after="general")
-    group._addoption('-v', '--verbose', action="count",
-                     dest="verbose", default=0, help="increase verbosity."),
-    group._addoption('-q', '--quiet', action="count",
-                     dest="quiet", default=0, help="decrease verbosity."),
-    group._addoption('-r',
-                     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, "
-                     "(p)passed, (P)passed with output, (a)all except pP. "
-                     "Warnings are displayed at all times except when "
-                     "--disable-warnings is set")
-    group._addoption('--disable-warnings', '--disable-pytest-warnings', default=False,
-                     dest='disable_warnings', action='store_true',
-                     help='disable warnings summary')
-    group._addoption('-l', '--showlocals',
-                     action="store_true", dest="showlocals", default=False,
-                     help="show locals in tracebacks (disabled by default).")
-    group._addoption('--tb', metavar="style",
-                     action="store", dest="tbstyle", default='auto',
-                     choices=['auto', 'long', 'short', 'no', 'line', 'native'],
-                     help="traceback print mode (auto/long/short/line/native/no).")
-    group._addoption('--fulltrace', '--full-trace',
-                     action="store_true", default=False,
-                     help="don't cut any tracebacks (default is to cut).")
-    group._addoption('--color', metavar="color",
-                     action="store", dest="color", default='auto',
-                     choices=['yes', 'no', 'auto'],
-                     help="color terminal output (yes/no/auto).")
+    group._addoption(
+        "-v",
+        "--verbose",
+        action="count",
+        default=0,
+        dest="verbose",
+        help="increase verbosity.",
+    ),
+    group._addoption(
+        "-q",
+        "--quiet",
+        action=MoreQuietAction,
+        default=0,
+        dest="verbose",
+        help="decrease verbosity.",
+    ),
+    group._addoption(
+        "--verbosity", dest="verbose", type=int, default=0, help="set verbosity"
+    )
+    group._addoption(
+        "-r",
+        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, "
+        "(p)passed, (P)passed with output, (a)all except pP. "
+        "Warnings are displayed at all times except when "
+        "--disable-warnings is set",
+    )
+    group._addoption(
+        "--disable-warnings",
+        "--disable-pytest-warnings",
+        default=False,
+        dest="disable_warnings",
+        action="store_true",
+        help="disable warnings summary",
+    )
+    group._addoption(
+        "-l",
+        "--showlocals",
+        action="store_true",
+        dest="showlocals",
+        default=False,
+        help="show locals in tracebacks (disabled by default).",
+    )
+    group._addoption(
+        "--tb",
+        metavar="style",
+        action="store",
+        dest="tbstyle",
+        default="auto",
+        choices=["auto", "long", "short", "no", "line", "native"],
+        help="traceback print mode (auto/long/short/line/native/no).",
+    )
+    group._addoption(
+        "--show-capture",
+        action="store",
+        dest="showcapture",
+        choices=["no", "stdout", "stderr", "log", "all"],
+        default="all",
+        help="Controls how captured stdout/stderr/log is shown on failed tests. "
+        "Default is 'all'.",
+    )
+    group._addoption(
+        "--fulltrace",
+        "--full-trace",
+        action="store_true",
+        default=False,
+        help="don't cut any tracebacks (default is to cut).",
+    )
+    group._addoption(
+        "--color",
+        metavar="color",
+        action="store",
+        dest="color",
+        default="auto",
+        choices=["yes", "no", "auto"],
+        help="color terminal output (yes/no/auto).",
+    )
 
-    parser.addini("console_output_style",
-                  help="console output: classic or with additional progress information (classic|progress).",
-                  default='progress')
+    parser.addini(
+        "console_output_style",
+        help="console output: classic or with additional progress information (classic|progress).",
+        default="progress",
+    )
 
 
 def pytest_configure(config):
-    config.option.verbose -= config.option.quiet
     reporter = TerminalReporter(config, sys.stdout)
-    config.pluginmanager.register(reporter, 'terminalreporter')
+    config.pluginmanager.register(reporter, "terminalreporter")
     if config.option.debug or config.option.traceconfig:
+
         def mywriter(tags, args):
             msg = " ".join(map(str, args))
             reporter.write_line("[traceconfig] " + msg)
+
         config.trace.root.setprocessor("pytest:config", mywriter)
 
 
 def getreportopt(config):
     reportopts = ""
     reportchars = config.option.reportchars
-    if not config.option.disable_warnings and 'w' not in reportchars:
-        reportchars += 'w'
-    elif config.option.disable_warnings and 'w' in reportchars:
-        reportchars = reportchars.replace('w', '')
+    if not config.option.disable_warnings and "w" not in reportchars:
+        reportchars += "w"
+    elif config.option.disable_warnings and "w" in reportchars:
+        reportchars = reportchars.replace("w", "")
     if reportchars:
         for char in reportchars:
-            if char not in reportopts and char != 'a':
+            if char not in reportopts and char != "a":
                 reportopts += char
-            elif char == 'a':
-                reportopts = 'fEsxXw'
+            elif char == "a":
+                reportopts = "fEsxXw"
     return reportopts
 
 
 def pytest_report_teststatus(report):
     if report.passed:
         letter = "."
     elif report.skipped:
         letter = "s"
     elif report.failed:
         letter = "F"
         if report.when != "call":
             letter = "f"
     return report.outcome, letter, report.outcome.upper()
 
 
-class WarningReport:
+class WarningReport(object):
     """
     Simple structure to hold warnings information captured by ``pytest_logwarning``.
     """
 
     def __init__(self, code, message, nodeid=None, fslocation=None):
         """
         :param code: unused
         :param str message: user friendly message about the warning
@@ -118,25 +208,27 @@ class WarningReport:
         of a warning, or None.
         """
         if self.nodeid:
             return self.nodeid
         if self.fslocation:
             if isinstance(self.fslocation, tuple) and len(self.fslocation) >= 2:
                 filename, linenum = self.fslocation[:2]
                 relpath = py.path.local(filename).relto(config.invocation_dir)
-                return '%s:%s' % (relpath, linenum)
+                return "%s:%s" % (relpath, linenum)
             else:
                 return str(self.fslocation)
         return None
 
 
-class TerminalReporter:
+class TerminalReporter(object):
+
     def __init__(self, config, file=None):
         import _pytest.config
+
         self.config = config
         self.verbosity = self.config.option.verbose
         self.showheader = self.verbosity >= 0
         self.showfspath = self.verbosity >= 0
         self.showlongtestinfo = self.verbosity > 0
         self._numcollected = 0
         self._session = None
 
@@ -147,21 +239,31 @@ class TerminalReporter:
         self._tw = _pytest.config.create_terminal_writer(config, file)
         # self.writer will be deprecated in pytest-3.4
         self.writer = self._tw
         self._screen_width = self._tw.fullwidth
         self.currentfspath = None
         self.reportchars = getreportopt(config)
         self.hasmarkup = self._tw.hasmarkup
         self.isatty = file.isatty()
-        self._progress_items_reported = 0
-        self._show_progress_info = self.config.getini('console_output_style') == 'progress'
+        self._progress_nodeids_reported = set()
+        self._show_progress_info = self._determine_show_progress_info()
+
+    def _determine_show_progress_info(self):
+        """Return True if we should display progress information based on the current config"""
+        # do not show progress if we are not capturing output (#3038)
+        if self.config.getoption("capture") == "no":
+            return False
+        # do not show progress if we are showing fixture setup/teardown
+        if self.config.getoption("setupshow"):
+            return False
+        return self.config.getini("console_output_style") == "progress"
 
     def hasopt(self, char):
-        char = {'xfailed': 'x', 'skipped': 's'}.get(char, char)
+        char = {"xfailed": "x", "skipped": "s"}.get(char, char)
         return char in self.reportchars
 
     def write_fspath_result(self, nodeid, res):
         fspath = self.config.rootdir.join(nodeid.split("::")[0])
         if fspath != self.currentfspath:
             if self.currentfspath is not None:
                 self._write_progress_information_filling_space()
             self.currentfspath = fspath
@@ -173,17 +275,16 @@ class TerminalReporter:
     def write_ensure_prefix(self, prefix, extra="", **kwargs):
         if self.currentfspath != prefix:
             self._tw.line()
             self.currentfspath = prefix
             self._tw.write(prefix)
         if extra:
             self._tw.write(extra, **kwargs)
             self.currentfspath = -2
-            self._write_progress_information_filling_space()
 
     def ensure_newline(self):
         if self.currentfspath:
             self._tw.line()
             self.currentfspath = None
 
     def write(self, content, **markup):
         self._tw.write(content, **markup)
@@ -198,22 +299,22 @@ class TerminalReporter:
         """
         Rewinds the terminal cursor to the beginning and writes the given line.
 
         :kwarg erase: if True, will also add spaces until the full terminal width to ensure
             previous lines are properly erased.
 
         The rest of the keyword arguments are markup instructions.
         """
-        erase = markup.pop('erase', False)
+        erase = markup.pop("erase", False)
         if erase:
             fill_count = self._tw.fullwidth - len(line) - 1
-            fill = ' ' * fill_count
+            fill = " " * fill_count
         else:
-            fill = ''
+            fill = ""
         line = str(line)
         self._tw.write("\r" + line + fill, **markup)
 
     def write_sep(self, sep, title=None, **markup):
         self.ensure_newline()
         self._tw.sep(sep, title, **markup)
 
     def section(self, title, sep="=", **kw):
@@ -224,30 +325,31 @@ class TerminalReporter:
 
     def pytest_internalerror(self, excrepr):
         for line in six.text_type(excrepr).split("\n"):
             self.write_line("INTERNALERROR> " + line)
         return 1
 
     def pytest_logwarning(self, code, fslocation, message, nodeid):
         warnings = self.stats.setdefault("warnings", [])
-        warning = WarningReport(code=code, fslocation=fslocation,
-                                message=message, nodeid=nodeid)
+        warning = WarningReport(
+            code=code, fslocation=fslocation, message=message, nodeid=nodeid
+        )
         warnings.append(warning)
 
     def pytest_plugin_registered(self, plugin):
         if self.config.option.traceconfig:
             msg = "PLUGIN registered: %s" % (plugin,)
             # XXX this event may happen during setup/teardown time
             #     which unfortunately captures our output here
             #     which garbles our output if we use self.write_line
             self.write_line(msg)
 
     def pytest_deselected(self, items):
-        self.stats.setdefault('deselected', []).extend(items)
+        self.stats.setdefault("deselected", []).extend(items)
 
     def pytest_runtest_logstart(self, nodeid, location):
         # ensure that the path is printed before the
         # 1st test of a module starts running
         if self.showlongtestinfo:
             line = self._locationline(nodeid, *location)
             self.write_ensure_prefix(line, "")
         elif self.showfspath:
@@ -262,75 +364,81 @@ class TerminalReporter:
             word, markup = word
         else:
             markup = None
         self.stats.setdefault(cat, []).append(rep)
         self._tests_ran = True
         if not letter and not word:
             # probably passed setup/teardown
             return
-        running_xdist = hasattr(rep, 'node')
-        self._progress_items_reported += 1
+        running_xdist = hasattr(rep, "node")
         if self.verbosity <= 0:
             if not running_xdist and self.showfspath:
                 self.write_fspath_result(rep.nodeid, letter)
             else:
                 self._tw.write(letter)
-            self._write_progress_if_past_edge()
         else:
+            self._progress_nodeids_reported.add(rep.nodeid)
             if markup is None:
                 if rep.passed:
-                    markup = {'green': True}
+                    markup = {"green": True}
                 elif rep.failed:
-                    markup = {'red': True}
+                    markup = {"red": True}
                 elif rep.skipped:
-                    markup = {'yellow': True}
+                    markup = {"yellow": True}
                 else:
                     markup = {}
             line = self._locationline(rep.nodeid, *rep.location)
             if not running_xdist:
                 self.write_ensure_prefix(line, word, **markup)
+                if self._show_progress_info:
+                    self._write_progress_information_filling_space()
             else:
                 self.ensure_newline()
                 self._tw.write("[%s]" % rep.node.gateway.id)
                 if self._show_progress_info:
-                    self._tw.write(self._get_progress_information_message() + " ", cyan=True)
+                    self._tw.write(
+                        self._get_progress_information_message() + " ", cyan=True
+                    )
                 else:
-                    self._tw.write(' ')
+                    self._tw.write(" ")
                 self._tw.write(word, **markup)
                 self._tw.write(" " + line)
                 self.currentfspath = -2
 
-    def _write_progress_if_past_edge(self):
-        if not self._show_progress_info:
-            return
-        last_item = self._progress_items_reported == self._session.testscollected
-        if last_item:
-            self._write_progress_information_filling_space()
-            return
+    def pytest_runtest_logfinish(self, nodeid):
+        if self.verbosity <= 0 and self._show_progress_info:
+            self._progress_nodeids_reported.add(nodeid)
+            last_item = len(
+                self._progress_nodeids_reported
+            ) == self._session.testscollected
+            if last_item:
+                self._write_progress_information_filling_space()
+            else:
+                past_edge = self._tw.chars_on_current_line + self._PROGRESS_LENGTH + 1 >= self._screen_width
+                if past_edge:
+                    msg = self._get_progress_information_message()
+                    self._tw.write(msg + "\n", cyan=True)
 
-        past_edge = self._tw.chars_on_current_line + self._PROGRESS_LENGTH + 1 >= self._screen_width
-        if past_edge:
-            msg = self._get_progress_information_message()
-            self._tw.write(msg + '\n', cyan=True)
-
-    _PROGRESS_LENGTH = len(' [100%]')
+    _PROGRESS_LENGTH = len(" [100%]")
 
     def _get_progress_information_message(self):
+        if self.config.getoption("capture") == "no":
+            return ""
         collected = self._session.testscollected
         if collected:
-            progress = self._progress_items_reported * 100 // collected
-            return ' [{:3d}%]'.format(progress)
-        return ' [100%]'
+            progress = len(self._progress_nodeids_reported) * 100 // collected
+            return " [{:3d}%]".format(progress)
+        return " [100%]"
 
     def _write_progress_information_filling_space(self):
-        if not self._show_progress_info:
-            return
         msg = self._get_progress_information_message()
-        fill = ' ' * (self._tw.fullwidth - self._tw.chars_on_current_line - len(msg) - 1)
+        fill = " " * (
+            self._tw.fullwidth - self._tw.chars_on_current_line - len(msg) - 1
+        )
         self.write(fill + msg, cyan=True)
 
     def pytest_collection(self):
         if not self.isatty and self.config.option.verbose >= 1:
             self.write("collecting ... ", bold=True)
 
     def pytest_collectreport(self, report):
         if report.failed:
@@ -342,99 +450,110 @@ class TerminalReporter:
         if self.isatty:
             # self.write_fspath_result(report.nodeid, 'E')
             self.report_collect()
 
     def report_collect(self, final=False):
         if self.config.option.verbose < 0:
             return
 
-        errors = len(self.stats.get('error', []))
-        skipped = len(self.stats.get('skipped', []))
+        errors = len(self.stats.get("error", []))
+        skipped = len(self.stats.get("skipped", []))
+        deselected = len(self.stats.get("deselected", []))
         if final:
             line = "collected "
         else:
             line = "collecting "
-        line += str(self._numcollected) + " item" + ('' if self._numcollected == 1 else 's')
+        line += str(self._numcollected) + " item" + (
+            "" if self._numcollected == 1 else "s"
+        )
         if errors:
             line += " / %d errors" % errors
+        if deselected:
+            line += " / %d deselected" % deselected
         if skipped:
             line += " / %d skipped" % skipped
         if self.isatty:
             self.rewrite(line, bold=True, erase=True)
             if final:
-                self.write('\n')
+                self.write("\n")
         else:
             self.write_line(line)
 
+    @pytest.hookimpl(trylast=True)
     def pytest_collection_modifyitems(self):
         self.report_collect(True)
 
     @pytest.hookimpl(trylast=True)
     def pytest_sessionstart(self, session):
         self._session = session
         self._sessionstarttime = time.time()
         if not self.showheader:
             return
         self.write_sep("=", "test session starts", bold=True)
         verinfo = platform.python_version()
         msg = "platform %s -- Python %s" % (sys.platform, verinfo)
-        if hasattr(sys, 'pypy_version_info'):
+        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 += ", 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):
+            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)
         self.write_line(msg)
         lines = self.config.hook.pytest_report_header(
-            config=self.config, startdir=self.startdir)
+            config=self.config, startdir=self.startdir
+        )
         self._write_report_lines_from_hooks(lines)
 
     def _write_report_lines_from_hooks(self, lines):
         lines.reverse()
-        for line in flatten(lines):
+        for line in collapse(lines):
             self.write_line(line)
 
     def pytest_report_header(self, config):
         inifile = ""
         if config.inifile:
             inifile = " " + config.rootdir.bestrelpath(config.inifile)
         lines = ["rootdir: %s, inifile:%s" % (config.rootdir, inifile)]
 
         plugininfo = config.pluginmanager.list_plugin_distinfo()
         if plugininfo:
 
-            lines.append(
-                "plugins: %s" % ", ".join(_plugin_nameversions(plugininfo)))
+            lines.append("plugins: %s" % ", ".join(_plugin_nameversions(plugininfo)))
         return lines
 
     def pytest_collection_finish(self, session):
         if self.config.option.collectonly:
             self._printcollecteditems(session.items)
-            if self.stats.get('failed'):
+            if self.stats.get("failed"):
                 self._tw.sep("!", "collection failures")
-                for rep in self.stats.get('failed'):
+                for rep in self.stats.get("failed"):
                     rep.toterminal(self._tw)
                 return 1
             return 0
         lines = self.config.hook.pytest_report_collectionfinish(
-            config=self.config, startdir=self.startdir, items=session.items)
+            config=self.config, startdir=self.startdir, items=session.items
+        )
         self._write_report_lines_from_hooks(lines)
 
     def _printcollecteditems(self, items):
         # to print out items and their parent collectors
         # we take care to leave out Instances aka ()
         # because later versions are going to get rid of them anyway
         if self.config.option.verbose < 0:
             if self.config.option.verbose < -1:
                 counts = {}
                 for item in items:
-                    name = item.nodeid.split('::', 1)[0]
+                    name = item.nodeid.split("::", 1)[0]
                     counts[name] = counts.get(name, 0) + 1
                 for name, count in sorted(counts.items()):
                     self._tw.line("%s: %d" % (name, count))
             else:
                 for item in items:
                     nodeid = item.nodeid
                     nodeid = nodeid.replace("::()::", "::")
                     self._tw.line(nodeid)
@@ -455,70 +574,83 @@ class TerminalReporter:
                 self._tw.line("%s%s" % (indent, col))
 
     @pytest.hookimpl(hookwrapper=True)
     def pytest_sessionfinish(self, exitstatus):
         outcome = yield
         outcome.get_result()
         self._tw.line("")
         summary_exit_codes = (
-            EXIT_OK, EXIT_TESTSFAILED, EXIT_INTERRUPTED, EXIT_USAGEERROR,
-            EXIT_NOTESTSCOLLECTED)
+            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.summary_passes()
+            self.config.hook.pytest_terminal_summary(
+                terminalreporter=self, exitstatus=exitstatus
+            )
         if exitstatus == EXIT_INTERRUPTED:
             self._report_keyboardinterrupt()
             del self._keyboardinterrupt_memo
-        self.summary_deselected()
         self.summary_stats()
 
+    @pytest.hookimpl(hookwrapper=True)
+    def pytest_terminal_summary(self):
+        self.summary_errors()
+        self.summary_failures()
+        yield
+        self.summary_warnings()
+        self.summary_passes()
+
     def pytest_keyboard_interrupt(self, excinfo):
         self._keyboardinterrupt_memo = excinfo.getrepr(funcargs=True)
 
     def pytest_unconfigure(self):
-        if hasattr(self, '_keyboardinterrupt_memo'):
+        if hasattr(self, "_keyboardinterrupt_memo"):
             self._report_keyboardinterrupt()
 
     def _report_keyboardinterrupt(self):
         excrepr = self._keyboardinterrupt_memo
         msg = excrepr.reprcrash.message
         self.write_sep("!", msg)
         if "KeyboardInterrupt" in msg:
             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)
+                self._tw.line(
+                    "(to show a full traceback on KeyboardInterrupt use --fulltrace)",
+                    yellow=True,
+                )
 
     def _locationline(self, nodeid, fspath, lineno, domain):
+
         def mkrel(nodeid):
             line = self.config.cwd_relative_nodeid(nodeid)
             if domain and line.endswith(domain):
                 line = line[:-len(domain)]
                 values = domain.split("[")
-                values[0] = values[0].replace('.', '::')  # don't replace '.' in params
+                values[0] = values[0].replace(".", "::")  # don't replace '.' in params
                 line += "[".join(values)
             return line
+
         # collect_fspath comes from testid which has a "/"-normalized path
 
         if fspath:
             res = mkrel(nodeid).replace("::()", "")  # parens-normalization
             if nodeid.split("::")[0] != fspath.replace("\\", nodes.SEP):
                 res += " <- " + self.startdir.bestrelpath(fspath)
         else:
             res = "[location]"
         return res + " "
 
     def _getfailureheadline(self, rep):
-        if hasattr(rep, 'location'):
+        if hasattr(rep, "location"):
             fspath, lineno, domain = rep.location
             return domain
         else:
             return "test session"  # XXX?
 
     def _getcrashline(self, rep):
         try:
             return str(rep.longrepr.reprcrash)
@@ -529,141 +661,135 @@ class TerminalReporter:
                 return ""
 
     #
     # summaries for sessionfinish
     #
     def getreports(self, name):
         values = []
         for x in self.stats.get(name, []):
-            if not hasattr(x, '_pdbshown'):
+            if not hasattr(x, "_pdbshown"):
                 values.append(x)
         return values
 
     def summary_warnings(self):
         if self.hasopt("w"):
             all_warnings = self.stats.get("warnings")
             if not all_warnings:
                 return
 
-            grouped = itertools.groupby(all_warnings, key=lambda wr: wr.get_location(self.config))
+            grouped = itertools.groupby(
+                all_warnings, key=lambda wr: wr.get_location(self.config)
+            )
 
             self.write_sep("=", "warnings summary", yellow=True, bold=False)
             for location, warning_records in grouped:
-                self._tw.line(str(location) or '<undetermined location>')
+                self._tw.line(str(location) if location else "<undetermined location>")
                 for w in warning_records:
                     lines = w.message.splitlines()
-                    indented = '\n'.join('  ' + x for x in lines)
+                    indented = "\n".join("  " + x for x in lines)
                     self._tw.line(indented)
                 self._tw.line()
-            self._tw.line('-- Docs: http://doc.pytest.org/en/latest/warnings.html')
+            self._tw.line("-- Docs: http://doc.pytest.org/en/latest/warnings.html")
 
     def summary_passes(self):
         if self.config.option.tbstyle != "no":
             if self.hasopt("P"):
-                reports = self.getreports('passed')
+                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 print_teardown_sections(self, rep):
         for secname, content in rep.sections:
-            if 'teardown' in secname:
-                self._tw.sep('-', secname)
+            if "teardown" in secname:
+                self._tw.sep("-", secname)
                 if content[-1:] == "\n":
                     content = content[:-1]
                 self._tw.line(content)
 
     def summary_failures(self):
         if self.config.option.tbstyle != "no":
-            reports = self.getreports('failed')
+            reports = self.getreports("failed")
             if not reports:
                 return
             self.write_sep("=", "FAILURES")
             for rep in reports:
                 if self.config.option.tbstyle == "line":
                     line = self._getcrashline(rep)
                     self.write_line(line)
                 else:
                     msg = self._getfailureheadline(rep)
-                    markup = {'red': True, 'bold': True}
+                    markup = {"red": True, "bold": True}
                     self.write_sep("_", msg, **markup)
                     self._outrep_summary(rep)
-                    for report in self.getreports(''):
-                        if report.nodeid == rep.nodeid and report.when == 'teardown':
+                    for report in self.getreports(""):
+                        if report.nodeid == rep.nodeid and report.when == "teardown":
                             self.print_teardown_sections(report)
 
     def summary_errors(self):
         if self.config.option.tbstyle != "no":
-            reports = self.getreports('error')
+            reports = self.getreports("error")
             if not reports:
                 return
             self.write_sep("=", "ERRORS")
-            for rep in self.stats['error']:
+            for rep in self.stats["error"]:
                 msg = self._getfailureheadline(rep)
-                if not hasattr(rep, 'when'):
+                if not hasattr(rep, "when"):
                     # collect
                     msg = "ERROR collecting " + msg
                 elif rep.when == "setup":
                     msg = "ERROR at setup of " + msg
                 elif rep.when == "teardown":
                     msg = "ERROR at teardown of " + msg
                 self.write_sep("_", msg)
                 self._outrep_summary(rep)
 
     def _outrep_summary(self, rep):
         rep.toterminal(self._tw)
+        showcapture = self.config.option.showcapture
+        if showcapture == "no":
+            return
         for secname, content in rep.sections:
+            if showcapture != "all" and showcapture not in secname:
+                continue
             self._tw.sep("-", secname)
             if content[-1:] == "\n":
                 content = content[:-1]
             self._tw.line(content)
 
     def summary_stats(self):
         session_duration = time.time() - self._sessionstarttime
         (line, color) = build_summary_stats_line(self.stats)
         msg = "%s in %.2f seconds" % (line, session_duration)
-        markup = {color: True, 'bold': True}
+        markup = {color: True, "bold": True}
 
         if self.verbosity >= 0:
             self.write_sep("=", msg, **markup)
         if self.verbosity == -1:
             self.write_line(msg, **markup)
 
-    def summary_deselected(self):
-        if 'deselected' in self.stats:
-            self.write_sep("=", "%d tests deselected" % (
-                len(self.stats['deselected'])), bold=True)
-
 
 def repr_pythonversion(v=None):
     if v is None:
         v = sys.version_info
     try:
         return "%s.%s.%s-%s-%s" % v
     except (TypeError, ValueError):
         return str(v)
 
 
-def flatten(values):
-    for x in values:
-        if isinstance(x, (list, tuple)):
-            for y in flatten(x):
-                yield y
-        else:
-            yield x
-
-
 def build_summary_stats_line(stats):
-    keys = ("failed passed skipped deselected "
-            "xfailed xpassed warnings error").split()
+    keys = (
+        "failed passed skipped deselected " "xfailed xpassed warnings error"
+    ).split()
     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:
@@ -671,33 +797,33 @@ def build_summary_stats_line(stats):
         if val:
             parts.append("%d %s" % (len(val), key))
 
     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'
+    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'
+        color = "yellow"
 
     return (line, color)
 
 
 def _plugin_nameversions(plugininfo):
     values = []
     for plugin, dist in plugininfo:
         # gets us name and version!
-        name = '{dist.project_name}-{dist.version}'.format(dist=dist)
+        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 values:
             values.append(name)
     return values
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/tmpdir.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/tmpdir.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/tmpdir.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/tmpdir.py
@@ -3,17 +3,17 @@ from __future__ import absolute_import, 
 
 import re
 
 import pytest
 import py
 from _pytest.monkeypatch import MonkeyPatch
 
 
-class TempdirFactory:
+class TempdirFactory(object):
     """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")
@@ -32,18 +32,19 @@ class TempdirFactory:
         """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)
         else:
-            p = py.path.local.make_numbered_dir(prefix=basename,
-                                                keep=0, rootdir=basetemp, lock_timeout=None)
+            p = py.path.local.make_numbered_dir(
+                prefix=basename, keep=0, rootdir=basetemp, lock_timeout=None
+            )
         self.trace("mktemp", p)
         return p
 
     def getbasetemp(self):
         """ return base temporary directory. """
         try:
             return self._basetemp
         except AttributeError:
@@ -54,35 +55,37 @@ class TempdirFactory:
                     basetemp.remove()
                 basetemp.mkdir()
             else:
                 temproot = py.path.local.get_temproot()
                 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)
+                    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)
+                basetemp = py.path.local.make_numbered_dir(
+                    prefix="pytest-", rootdir=rootdir
+                )
             self._basetemp = t = basetemp.realpath()
             self.trace("new basetemp", t)
             return t
 
     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
@@ -93,34 +96,36 @@ def pytest_configure(config):
 
     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)
+    mp.setattr(config, "_tmpdirhandler", t, raising=False)
+    mp.setattr(pytest, "ensuretemp", t.ensuretemp, raising=False)
 
 
-@pytest.fixture(scope='session')
+@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, 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`_
     path object.
+
+    .. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html
     """
     name = request.node.name
     name = re.sub(r"[\W]", "_", name)
     MAXVAL = 30
     if len(name) > MAXVAL:
         name = name[:MAXVAL]
     x = tmpdir_factory.mktemp(name, numbered=True)
     return x
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/unittest.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/unittest.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/unittest.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/unittest.py
@@ -24,60 +24,62 @@ def pytest_pycollect_makeitem(collector,
 
 class UnitTestCase(Class):
     # 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):
+        if getattr(cls, "__unittest_skip__", False):
             return  # skipped
-        setup = getattr(cls, 'setUpClass', None)
+        setup = getattr(cls, "setUpClass", None)
         if setup is not None:
             setup()
-        teardown = getattr(cls, 'tearDownClass', None)
+        teardown = getattr(cls, "tearDownClass", None)
         if teardown is not None:
             self.addfinalizer(teardown)
         super(UnitTestCase, self).setup()
 
     def collect(self):
         from unittest import TestLoader
+
         cls = self.obj
         if not getattr(cls, "__test__", True):
             return
         self.session._fixturemanager.parsefactories(self, unittest=True)
         loader = TestLoader()
         module = self.getparent(Module).obj
         foundsomething = False
         for name in loader.getTestCaseNames(self.obj):
             x = getattr(self.obj, name)
-            if not getattr(x, '__test__', True):
+            if not getattr(x, "__test__", True):
                 continue
-            funcobj = getattr(x, 'im_func', x)
+            funcobj = getattr(x, "im_func", x)
             transfer_markers(funcobj, cls, module)
-            yield TestCaseFunction(name, parent=self)
+            yield TestCaseFunction(name, parent=self, callobj=funcobj)
             foundsomething = True
 
         if not foundsomething:
-            runtest = getattr(self.obj, 'runTest', None)
+            runtest = getattr(self.obj, "runTest", None)
             if runtest is not None:
                 ut = sys.modules.get("twisted.trial.unittest", None)
                 if ut is None or runtest != ut.TestCase.runTest:
-                    yield TestCaseFunction('runTest', parent=self)
+                    yield TestCaseFunction("runTest", parent=self)
 
 
 class TestCaseFunction(Function):
+    nofuncargs = True
     _excinfo = None
 
     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'):
+        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
@@ -86,47 +88,53 @@ class TestCaseFunction(Function):
         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'):
+        if hasattr(self._testcase, "teardown_method"):
             self._testcase.teardown_method(self._obj)
         # Allow garbage collection on TestCase instance attributes.
         self._testcase = None
         self._obj = None
 
     def startTest(self, testcase):
         pass
 
     def _addexcinfo(self, rawexcinfo):
         # unwrap potential exception info (see twisted trial support below)
-        rawexcinfo = getattr(rawexcinfo, '_rawexcinfo', rawexcinfo)
+        rawexcinfo = getattr(rawexcinfo, "_rawexcinfo", rawexcinfo)
         try:
             excinfo = _pytest._code.ExceptionInfo(rawexcinfo)
         except TypeError:
             try:
                 try:
                     values = traceback.format_exception(*rawexcinfo)
-                    values.insert(0, "NOTE: Incompatible Exception Representation, "
-                                  "displaying natively:\n\n")
+                    values.insert(
+                        0,
+                        "NOTE: Incompatible Exception Representation, "
+                        "displaying natively:\n\n",
+                    )
                     fail("".join(values), pytrace=False)
                 except (fail.Exception, KeyboardInterrupt):
                     raise
                 except:  # noqa
-                    fail("ERROR: Unknown Incompatible Exception "
-                         "representation:\n%r" % (rawexcinfo,), pytrace=False)
+                    fail(
+                        "ERROR: Unknown Incompatible Exception "
+                        "representation:\n%r" % (rawexcinfo,),
+                        pytrace=False,
+                    )
             except KeyboardInterrupt:
                 raise
             except fail.Exception:
                 excinfo = _pytest._code.ExceptionInfo()
-        self.__dict__.setdefault('_excinfo', []).append(excinfo)
+        self.__dict__.setdefault("_excinfo", []).append(excinfo)
 
     def addError(self, testcase, rawexcinfo):
         self._addexcinfo(rawexcinfo)
 
     def addFailure(self, testcase, rawexcinfo):
         self._addexcinfo(rawexcinfo)
 
     def addSkip(self, testcase, reason):
@@ -150,21 +158,25 @@ class TestCaseFunction(Function):
 
     def stopTest(self, testcase):
         pass
 
     def _handle_skip(self):
         # implements the skipping machinery (see #2137)
         # analog to pythons Lib/unittest/case.py:run
         testMethod = getattr(self._testcase, self._testcase._testMethodName)
-        if (getattr(self._testcase.__class__, "__unittest_skip__", False) or
-                getattr(testMethod, "__unittest_skip__", False)):
+        if (
+            getattr(self._testcase.__class__, "__unittest_skip__", False)
+            or getattr(testMethod, "__unittest_skip__", False)
+        ):
             # If the class or method was skipped.
-            skip_why = (getattr(self._testcase.__class__, '__unittest_skip_why__', '') or
-                        getattr(testMethod, '__unittest_skip_why__', ''))
+            skip_why = (
+                getattr(self._testcase.__class__, "__unittest_skip_why__", "")
+                or getattr(testMethod, "__unittest_skip_why__", "")
+            )
             try:  # PY3, unittest2 on PY2
                 self._testcase._addSkip(self, self._testcase, skip_why)
             except TypeError:  # PY2
                 if sys.version_info[0] != 2:
                     raise
                 self._testcase._addSkip(self, skip_why)
             return True
         return False
@@ -176,62 +188,66 @@ class TestCaseFunction(Function):
             # disables tearDown and cleanups for post mortem debugging (see #1890)
             if self._handle_skip():
                 return
             self._testcase.debug()
 
     def _prunetraceback(self, excinfo):
         Function._prunetraceback(self, excinfo)
         traceback = excinfo.traceback.filter(
-            lambda x: not x.frame.f_globals.get('__unittest'))
+            lambda x: not x.frame.f_globals.get("__unittest")
+        )
         if traceback:
             excinfo.traceback = traceback
 
 
 @hookimpl(tryfirst=True)
 def pytest_runtest_makereport(item, call):
     if isinstance(item, TestCaseFunction):
         if item._excinfo:
             call.excinfo = item._excinfo.pop(0)
             try:
                 del call.result
             except AttributeError:
                 pass
 
+
 # twisted trial support
 
 
 @hookimpl(hookwrapper=True)
 def pytest_runtest_protocol(item):
-    if isinstance(item, TestCaseFunction) and \
-       'twisted.trial.unittest' in sys.modules:
-        ut = sys.modules['twisted.python.failure']
+    if isinstance(item, TestCaseFunction) and "twisted.trial.unittest" in sys.modules:
+        ut = sys.modules["twisted.python.failure"]
         Failure__init__ = ut.Failure.__init__
         check_testcase_implements_trial_reporter()
 
-        def excstore(self, exc_value=None, exc_type=None, exc_tb=None,
-                     captureVars=None):
+        def excstore(
+            self, exc_value=None, exc_type=None, exc_tb=None, captureVars=None
+        ):
             if exc_value is None:
                 self._rawexcinfo = sys.exc_info()
             else:
                 if exc_type is None:
                     exc_type = type(exc_value)
                 self._rawexcinfo = (exc_type, exc_value, exc_tb)
             try:
-                Failure__init__(self, exc_value, exc_type, exc_tb,
-                                captureVars=captureVars)
+                Failure__init__(
+                    self, exc_value, exc_type, exc_tb, captureVars=captureVars
+                )
             except TypeError:
                 Failure__init__(self, exc_value, exc_type, exc_tb)
 
         ut.Failure.__init__ = excstore
         yield
         ut.Failure.__init__ = Failure__init__
     else:
         yield
 
 
 def check_testcase_implements_trial_reporter(done=[]):
     if done:
         return
     from zope.interface import classImplements
     from twisted.trial.itrial import IReporter
+
     classImplements(TestCaseFunction, IReporter)
     done.append(1)
rename from testing/web-platform/tests/tools/third_party/pytest/_pytest/warnings.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/_pytest/warnings.py
--- a/testing/web-platform/tests/tools/third_party/pytest/_pytest/warnings.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/_pytest/warnings.py
@@ -7,23 +7,22 @@ import pytest
 
 from _pytest import compat
 
 
 def _setoption(wmod, arg):
     """
     Copy of the warning._setoption function but does not escape arguments.
     """
-    parts = arg.split(':')
+    parts = arg.split(":")
     if len(parts) > 5:
         raise wmod._OptionError("too many fields (max 5): %r" % (arg,))
     while len(parts) < 5:
-        parts.append('')
-    action, message, category, module, lineno = [s.strip()
-                                                 for s in parts]
+        parts.append("")
+    action, message, category, module, lineno = [s.strip() for s in parts]
     action = wmod._getaction(action)
     category = wmod._getcategory(category)
     if lineno:
         try:
             lineno = int(lineno)
             if lineno < 0:
                 raise ValueError
         except (ValueError, OverflowError):
@@ -31,66 +30,83 @@ def _setoption(wmod, arg):
     else:
         lineno = 0
     wmod.filterwarnings(action, message, category, module, lineno)
 
 
 def pytest_addoption(parser):
     group = parser.getgroup("pytest-warnings")
     group.addoption(
-        '-W', '--pythonwarnings', action='append',
-        help="set which warnings to report, see -W option of python itself.")
-    parser.addini("filterwarnings", type="linelist",
-                  help="Each line specifies a pattern for "
-                  "warnings.filterwarnings. "
-                  "Processed after -W and --pythonwarnings.")
+        "-W",
+        "--pythonwarnings",
+        action="append",
+        help="set which warnings to report, see -W option of python itself.",
+    )
+    parser.addini(
+        "filterwarnings",
+        type="linelist",
+        help="Each line specifies a pattern for "
+        "warnings.filterwarnings. "
+        "Processed after -W and --pythonwarnings.",
+    )
 
 
 @contextmanager
 def catch_warnings_for_item(item):
     """
     catches the warnings generated during setup/call/teardown execution
     of the given item and after it is done posts them as warnings to this
     item.
     """
-    args = item.config.getoption('pythonwarnings') or []
+    args = item.config.getoption("pythonwarnings") or []
     inifilters = item.config.getini("filterwarnings")
     with warnings.catch_warnings(record=True) as log:
         for arg in args:
             warnings._setoption(arg)
 
         for arg in inifilters:
             _setoption(warnings, arg)
 
-        mark = item.get_marker('filterwarnings')
-        if mark:
+        for mark in item.iter_markers(name="filterwarnings"):
             for arg in mark.args:
                 warnings._setoption(arg)
 
         yield
 
         for warning in log:
             warn_msg = warning.message
             unicode_warning = False
 
-            if compat._PY2 and any(isinstance(m, compat.UNICODE_TYPES) for m in warn_msg.args):
+            if (
+                compat._PY2
+                and any(isinstance(m, compat.UNICODE_TYPES) for m in warn_msg.args)
+            ):
                 new_args = []
                 for m in warn_msg.args:
-                    new_args.append(compat.ascii_escaped(m) if isinstance(m, compat.UNICODE_TYPES) else m)
+                    new_args.append(
+                        compat.ascii_escaped(m)
+                        if isinstance(m, compat.UNICODE_TYPES)
+                        else m
+                    )
                 unicode_warning = list(warn_msg.args) != new_args
                 warn_msg.args = new_args
 
             msg = warnings.formatwarning(
-                warn_msg, warning.category,
-                warning.filename, warning.lineno, warning.line)
+                warn_msg,
+                warning.category,
+                warning.filename,
+                warning.lineno,
+                warning.line,
+            )
             item.warn("unused", msg)
 
             if unicode_warning:
                 warnings.warn(
                     "Warning is using unicode non convertible to ascii, "
                     "converting to a safe representation:\n  %s" % msg,
-                    UnicodeWarning)
+                    UnicodeWarning,
+                )
 
 
 @pytest.hookimpl(hookwrapper=True)
 def pytest_runtest_protocol(item):
     with catch_warnings_for_item(item):
         yield
rename from testing/web-platform/tests/tools/third_party/pytest/pytest.py
rename to testing/web-platform/tests/tools/third_party/pytest/src/pytest.py
--- a/testing/web-platform/tests/tools/third_party/pytest/pytest.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/src/pytest.py
@@ -1,77 +1,72 @@
 # PYTHON_ARGCOMPLETE_OK
 """
 pytest: unit and functional testing with Python.
 """
 
 
 # else we are imported
 
-from _pytest.config import (
-    main, UsageError, cmdline,
-    hookspec, hookimpl
-)
+from _pytest.config import main, UsageError, cmdline, hookspec, hookimpl
 from _pytest.fixtures import fixture, yield_fixture
 from _pytest.assertion import register_assert_rewrite
 from _pytest.freeze_support import freeze_includes
 from _pytest import __version__
 from _pytest.debugging import pytestPDB as __pytestPDB
 from _pytest.recwarn import warns, deprecated_call
 from _pytest.outcomes import fail, skip, importorskip, exit, xfail
 from _pytest.mark import MARK_GEN as mark, param
-from _pytest.main import Item, Collector, File, Session
+from _pytest.main import Session
+from _pytest.nodes import Item, Collector, File
 from _pytest.fixtures import fillfixtures as _fillfuncargs
-from _pytest.python import (
-    Module, Class, Instance, Function, Generator,
-)
+from _pytest.python import Module, Class, Instance, Function, Generator
 
 from _pytest.python_api import approx, raises
 
 set_trace = __pytestPDB.set_trace
 
 __all__ = [
-    'main',
-    'UsageError',
-    'cmdline',
-    'hookspec',
-    'hookimpl',
-    '__version__',
-    'register_assert_rewrite',
-    'freeze_includes',
-    'set_trace',
-    'warns',
-    'deprecated_call',
-    'fixture',
-    'yield_fixture',
-    'fail',
-    'skip',
-    'xfail',
-    'importorskip',
-    'exit',
-    'mark',
-    'param',
-    'approx',
-    '_fillfuncargs',
-
-    'Item',
-    'File',
-    'Collector',
-    'Session',
-    'Module',
-    'Class',
-    'Instance',
-    'Function',
-    'Generator',
-    'raises',
-
-
+    "main",
+    "UsageError",
+    "cmdline",
+    "hookspec",
+    "hookimpl",
+    "__version__",
+    "register_assert_rewrite",
+    "freeze_includes",
+    "set_trace",
+    "warns",
+    "deprecated_call",
+    "fixture",
+    "yield_fixture",
+    "fail",
+    "skip",
+    "xfail",
+    "importorskip",
+    "exit",
+    "mark",
+    "param",
+    "approx",
+    "_fillfuncargs",
+    "Item",
+    "File",
+    "Collector",
+    "Session",
+    "Module",
+    "Class",
+    "Instance",
+    "Function",
+    "Generator",
+    "raises",
 ]
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     # if run as a script or by 'python -m pytest'
     # we trigger the below "else" condition by the following import
     import pytest
+
     raise SystemExit(pytest.main())
 else:
 
     from _pytest.compat import _setup_collect_fakemodule
+
     _setup_collect_fakemodule()
--- a/testing/web-platform/tests/tools/third_party/pytest/tasks/__init__.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/tasks/__init__.py
@@ -2,11 +2,9 @@
 Invoke tasks to help with pytest development and release process.
 """
 
 import invoke
 
 from . import generate
 
 
-ns = invoke.Collection(
-    generate,
-)
+ns = invoke.Collection(generate)
--- a/testing/web-platform/tests/tools/third_party/pytest/tasks/generate.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/tasks/generate.py
@@ -1,162 +1,118 @@
-import os
+"""
+Invoke development tasks.
+"""
 from pathlib import Path
 from subprocess import check_output, check_call
 
 import invoke
 
 
-@invoke.task(help={
-    'version': 'version being released',
-})
+@invoke.task(help={"version": "version being released"})
 def announce(ctx, version):
     """Generates a new release announcement entry in the docs."""
     # Get our list of authors
-    stdout = check_output(["git", "describe", "--abbrev=0", '--tags'])
-    stdout = stdout.decode('utf-8')
+    stdout = check_output(["git", "describe", "--abbrev=0", "--tags"])
+    stdout = stdout.decode("utf-8")
     last_version = stdout.strip()
 
-    stdout = check_output(["git", "log", "{}..HEAD".format(last_version), "--format=%aN"])
-    stdout = stdout.decode('utf-8')
+    stdout = check_output(
+        ["git", "log", "{}..HEAD".format(last_version), "--format=%aN"]
+    )
+    stdout = stdout.decode("utf-8")
 
     contributors = set(stdout.splitlines())
 
-    template_name = 'release.minor.rst' if version.endswith('.0') else 'release.patch.rst'
-    template_text = Path(__file__).parent.joinpath(template_name).read_text(encoding='UTF-8')
+    template_name = "release.minor.rst" if version.endswith(
+        ".0"
+    ) else "release.patch.rst"
+    template_text = Path(__file__).parent.joinpath(template_name).read_text(
+        encoding="UTF-8"
+    )
 
-    contributors_text = '\n'.join('* {}'.format(name) for name in sorted(contributors)) + '\n'
+    contributors_text = "\n".join(
+        "* {}".format(name) for name in sorted(contributors)
+    ) + "\n"
     text = template_text.format(version=version, contributors=contributors_text)
 
-    target = Path(__file__).parent.joinpath('../doc/en/announce/release-{}.rst'.format(version))
-    target.write_text(text, encoding='UTF-8')
+    target = Path(__file__).parent.joinpath(
+        "../doc/en/announce/release-{}.rst".format(version)
+    )
+    target.write_text(text, encoding="UTF-8")
     print("[generate.announce] Generated {}".format(target.name))
 
     # Update index with the new release entry
-    index_path = Path(__file__).parent.joinpath('../doc/en/announce/index.rst')
-    lines = index_path.read_text(encoding='UTF-8').splitlines()
-    indent = '   '
+    index_path = Path(__file__).parent.joinpath("../doc/en/announce/index.rst")
+    lines = index_path.read_text(encoding="UTF-8").splitlines()
+    indent = "   "
     for index, line in enumerate(lines):
-        if line.startswith('{}release-'.format(indent)):
+        if line.startswith("{}release-".format(indent)):
             new_line = indent + target.stem
             if line != new_line:
                 lines.insert(index, new_line)
-                index_path.write_text('\n'.join(lines) + '\n', encoding='UTF-8')
+                index_path.write_text("\n".join(lines) + "\n", encoding="UTF-8")
                 print("[generate.announce] Updated {}".format(index_path.name))
             else:
-                print("[generate.announce] Skip {} (already contains release)".format(index_path.name))
+                print(
+                    "[generate.announce] Skip {} (already contains release)".format(
+                        index_path.name
+                    )
+                )
             break
 
-    check_call(['git', 'add', str(target)])
+    check_call(["git", "add", str(target)])
 
 
 @invoke.task()
 def regen(ctx):
     """Call regendoc tool to update examples and pytest output in the docs."""
     print("[generate.regen] Updating docs")
-    check_call(['tox', '-e', 'regen'])
+    check_call(["tox", "-e", "regen"])
 
 
 @invoke.task()
 def make_tag(ctx, version):
-    """Create a new (local) tag for the release, only if the repository is clean."""
+    """Create a new, local tag for the release, only if the repository is clean."""
     from git import Repo
 
-    repo = Repo('.')
+    repo = Repo(".")
     if repo.is_dirty():
-        print('Current repository is dirty. Please commit any changes and try again.')
+        print("Current repository is dirty. Please commit any changes and try again.")
         raise invoke.Exit(code=2)
 
     tag_names = [x.name for x in repo.tags]
     if version in tag_names:
         print("[generate.make_tag] Delete existing tag {}".format(version))
         repo.delete_tag(version)
 
     print("[generate.make_tag] Create tag {}".format(version))
     repo.create_tag(version)
 
 
-@invoke.task()
-def devpi_upload(ctx, version, user, password=None):
-    """Creates and uploads a package to devpi for testing."""
-    if password:
-        print("[generate.devpi_upload] devpi login {}".format(user))
-        check_call(['devpi', 'login', user, '--password', password])
-
-    check_call(['devpi', 'use', 'https://devpi.net/{}/dev'.format(user)])
-    
-    env = os.environ.copy()
-    env['SETUPTOOLS_SCM_PRETEND_VERSION'] = version
-    check_call(['devpi', 'upload', '--formats', 'sdist,bdist_wheel'], env=env)
-    print("[generate.devpi_upload] package uploaded")
-
-
-@invoke.task(help={
-    'version': 'version being released',
-    'user': 'name of the user on devpi to stage the generated package',
-    'password': 'user password on devpi to stage the generated package '
-                '(if not given assumed logged in)',
-})
-def pre_release(ctx, version, user, password=None):
-    """Generates new docs, release announcements and uploads a new release to devpi for testing."""
+@invoke.task(help={"version": "version being released"})
+def pre_release(ctx, version):
+    """Generates new docs, release announcements and creates a local tag."""
     announce(ctx, version)
     regen(ctx)
     changelog(ctx, version, write_out=True)
 
-    msg = 'Preparing release version {}'.format(version)
-    check_call(['git', 'commit', '-a', '-m', msg])
-    
+    msg = "Preparing release version {}".format(version)
+    check_call(["git", "commit", "-a", "-m", msg])
+
     make_tag(ctx, version)
 
-    devpi_upload(ctx, version=version, user=user, password=password)
-    
     print()
-    print('[generate.pre_release] Please push your branch and open a PR.')
+    print("[generate.pre_release] Please push your branch and open a PR.")
 
 
-@invoke.task(help={
-    'version': 'version being released',
-    'user': 'name of the user on devpi to stage the generated package',
-    'pypi_name': 'name of the pypi configuration section in your ~/.pypirc',
-})
-def publish_release(ctx, version, user, pypi_name):
-    """Publishes a package previously created by the 'pre_release' command."""
-    from git import Repo
-    repo = Repo('.')
-    tag_names = [x.name for x in repo.tags]
-    if version not in tag_names:
-        print('Could not find tag for version {}, exiting...'.format(version))
-        raise invoke.Exit(code=2)
-
-    check_call(['devpi', 'use', 'https://devpi.net/{}/dev'.format(user)])
-    check_call(['devpi', 'push', 'pytest=={}'.format(version), 'pypi:{}'.format(pypi_name)])
-    check_call(['git', 'push', 'git@github.com:pytest-dev/pytest.git', version])
-
-    emails = [
-        'pytest-dev@python.org',
-        'python-announce-list@python.org'
-    ]
-    if version.endswith('.0'):
-        emails.append('testing-in-python@lists.idyll.org')
-    print('Version {} has been published to PyPI!'.format(version))
-    print()
-    print('Please send an email announcement with the contents from:')
-    print()
-    print('  doc/en/announce/release-{}.rst'.format(version))
-    print()
-    print('To the following mail lists:')
-    print()
-    print(' ', ','.join(emails))
-    print()
-    print('And announce it on twitter adding the #pytest hash tag.')
-
-
-@invoke.task(help={
-    'version': 'version being released',
-    'write_out': 'write changes to the actial changelog'
-})
+@invoke.task(
+    help={
+        "version": "version being released",
+        "write_out": "write changes to the actual changelog",
+    }
+)
 def changelog(ctx, version, write_out=False):
     if write_out:
         addopts = []
     else:
-        addopts = ['--draft']
-    check_call(['towncrier', '--version', version] + addopts)
-
+        addopts = ["--draft"]
+    check_call(["towncrier", "--yes", "--version", version] + addopts)
--- a/testing/web-platform/tests/tools/third_party/pytest/tasks/release.minor.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/tasks/release.minor.rst
@@ -1,14 +1,14 @@
 pytest-{version}
 =======================================
 
 The pytest team is proud to announce the {version} release!
 
-pytest is a mature Python testing tool with more than a 1600 tests
+pytest is a mature Python testing tool with more than a 2000 tests
 against itself, passing on many different interpreters and platforms.
 
 This release contains a number of bugs fixes and improvements, so users are encouraged
 to take a look at the CHANGELOG:
 
     http://doc.pytest.org/en/latest/changelog.html
 
 For complete documentation, please visit:
--- a/testing/web-platform/tests/tools/third_party/pytest/tasks/release.patch.rst
+++ b/testing/web-platform/tests/tools/third_party/pytest/tasks/release.patch.rst
@@ -1,17 +1,17 @@
 pytest-{version}
 =======================================
 
 pytest {version} has just been released to PyPI.
 
 This is a bug-fix release, being a drop-in replacement. To upgrade::
 
   pip install --upgrade pytest
-  
+
 The full changelog is available at http://doc.pytest.org/en/latest/changelog.html.
 
 Thanks to all who contributed to this release, among them:
 
 {contributors}
 
 Happy testing,
 The pytest Development Team
--- a/testing/web-platform/tests/tools/third_party/pytest/tasks/requirements.txt
+++ b/testing/web-platform/tests/tools/third_party/pytest/tasks/requirements.txt
@@ -1,5 +1,6 @@
-invoke
-tox
+-e .
 gitpython
+invoke
 towncrier
+tox
 wheel
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/acceptance_test.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/acceptance_test.py
@@ -1,511 +1,548 @@
 # -*- coding: utf-8 -*-
 from __future__ import absolute_import, division, print_function
 import os
 import sys
+import types
+
+import six
 
 import _pytest._code
 import py
 import pytest
 from _pytest.main import EXIT_NOTESTSCOLLECTED, EXIT_USAGEERROR
 
 
 class TestGeneralUsage(object):
+
     def test_config_error(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_configure(config):
                 import pytest
                 raise pytest.UsageError("hello")
-        """)
+        """
+        )
         result = testdir.runpytest(testdir.tmpdir)
         assert result.ret != 0
-        result.stderr.fnmatch_lines([
-            '*ERROR: hello'
-        ])
+        result.stderr.fnmatch_lines(["*ERROR: hello"])
 
     def test_root_conftest_syntax_error(self, testdir):
         testdir.makepyfile(conftest="raise SyntaxError\n")
         result = testdir.runpytest()
         result.stderr.fnmatch_lines(["*raise SyntaxError*"])
         assert result.ret != 0
 
     def test_early_hook_error_issue38_1(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_sessionstart():
                 0 / 0
-        """)
+        """
+        )
         result = testdir.runpytest(testdir.tmpdir)
         assert result.ret != 0
         # tracestyle is native by default for hook failures
-        result.stdout.fnmatch_lines([
-            '*INTERNALERROR*File*conftest.py*line 2*',
-            '*0 / 0*',
-        ])
+        result.stdout.fnmatch_lines(
+            ["*INTERNALERROR*File*conftest.py*line 2*", "*0 / 0*"]
+        )
         result = testdir.runpytest(testdir.tmpdir, "--fulltrace")
         assert result.ret != 0
         # tracestyle is native by default for hook failures
-        result.stdout.fnmatch_lines([
-            '*INTERNALERROR*def pytest_sessionstart():*',
-            '*INTERNALERROR*0 / 0*',
-        ])
+        result.stdout.fnmatch_lines(
+            ["*INTERNALERROR*def pytest_sessionstart():*", "*INTERNALERROR*0 / 0*"]
+        )
 
     def test_early_hook_configure_error_issue38(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_configure():
                 0 / 0
-        """)
+        """
+        )
         result = testdir.runpytest(testdir.tmpdir)
         assert result.ret != 0
         # here we get it on stderr
-        result.stderr.fnmatch_lines([
-            '*INTERNALERROR*File*conftest.py*line 2*',
-            '*0 / 0*',
-        ])
+        result.stderr.fnmatch_lines(
+            ["*INTERNALERROR*File*conftest.py*line 2*", "*0 / 0*"]
+        )
 
     def test_file_not_found(self, testdir):
         result = testdir.runpytest("asd")
         assert result.ret != 0
         result.stderr.fnmatch_lines(["ERROR: file not found*asd"])
 
     def test_file_not_found_unconfigure_issue143(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_configure():
                 print("---configure")
             def pytest_unconfigure():
                 print("---unconfigure")
-        """)
+        """
+        )
         result = testdir.runpytest("-s", "asd")
         assert result.ret == 4  # EXIT_USAGEERROR
         result.stderr.fnmatch_lines(["ERROR: file not found*asd"])
-        result.stdout.fnmatch_lines([
-            "*---configure",
-            "*---unconfigure",
-        ])
+        result.stdout.fnmatch_lines(["*---configure", "*---unconfigure"])
 
     def test_config_preparse_plugin_option(self, testdir):
-        testdir.makepyfile(pytest_xyz="""
+        testdir.makepyfile(
+            pytest_xyz="""
             def pytest_addoption(parser):
                 parser.addoption("--xyz", dest="xyz", action="store")
-        """)
-        testdir.makepyfile(test_one="""
+        """
+        )
+        testdir.makepyfile(
+            test_one="""
             def test_option(pytestconfig):
                 assert pytestconfig.option.xyz == "123"
-        """)
+        """
+        )
         result = testdir.runpytest("-p", "pytest_xyz", "--xyz=123", syspathinsert=True)
         assert result.ret == 0
-        result.stdout.fnmatch_lines([
-            '*1 passed*',
-        ])
+        result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_assertion_magic(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_this():
                 x = 0
                 assert x
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            ">       assert x",
-            "E       assert 0",
-        ])
+        result.stdout.fnmatch_lines([">       assert x", "E       assert 0"])
         assert result.ret == 1
 
     def test_nested_import_error(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
                 import import_fails
                 def test_this():
                     assert import_fails.a == 1
-        """)
+        """
+        )
         testdir.makepyfile(import_fails="import does_not_work")
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            # XXX on jython this fails:  ">   import import_fails",
-            "ImportError while importing test module*",
-            "*No module named *does_not_work*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                # XXX on jython this fails:  ">   import import_fails",
+                "ImportError while importing test module*",
+                "*No module named *does_not_work*",
+            ]
+        )
         assert result.ret == 2
 
     def test_not_collectable_arguments(self, testdir):
         p1 = testdir.makepyfile("")
         p2 = testdir.makefile(".pyc", "123")
         result = testdir.runpytest(p1, p2)
         assert result.ret
-        result.stderr.fnmatch_lines([
-            "*ERROR: not found:*%s" % (p2.basename,)
-        ])
+        result.stderr.fnmatch_lines(["*ERROR: not found:*%s" % (p2.basename,)])
 
     def test_issue486_better_reporting_on_conftest_load_failure(self, testdir):
         testdir.makepyfile("")
         testdir.makeconftest("import qwerty")
         result = testdir.runpytest("--help")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *--version*
             *warning*conftest.py*
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stderr.fnmatch_lines("""
+        result.stderr.fnmatch_lines(
+            """
             *ERROR*could not load*conftest.py*
-        """)
+        """
+        )
 
     def test_early_skip(self, testdir):
         testdir.mkdir("xyz")
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             def pytest_collect_directory():
                 pytest.skip("early")
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == EXIT_NOTESTSCOLLECTED
-        result.stdout.fnmatch_lines([
-            "*1 skip*"
-        ])
+        result.stdout.fnmatch_lines(["*1 skip*"])
 
     def test_issue88_initial_file_multinodes(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             class MyFile(pytest.File):
                 def collect(self):
                     return [MyItem("hello", parent=self)]
             def pytest_collect_file(path, parent):
                 return MyFile(path, parent)
             class MyItem(pytest.Item):
                 pass
-        """)
+        """
+        )
         p = testdir.makepyfile("def test_hello(): pass")
         result = testdir.runpytest(p, "--collect-only")
-        result.stdout.fnmatch_lines([
-            "*MyFile*test_issue88*",
-            "*Module*test_issue88*",
-        ])
+        result.stdout.fnmatch_lines(["*MyFile*test_issue88*", "*Module*test_issue88*"])
 
     def test_issue93_initialnode_importing_capturing(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import sys
             print ("should not be seen")
             sys.stderr.write("stder42\\n")
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == EXIT_NOTESTSCOLLECTED
         assert "should not be seen" not in result.stdout.str()
         assert "stderr42" not in result.stderr.str()
 
     def test_conftest_printing_shows_if_error(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             print ("should be seen")
             assert 0
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret != 0
         assert "should be seen" in result.stdout.str()
 
-    @pytest.mark.skipif(not hasattr(py.path.local, 'mksymlinkto'),
-                        reason="symlink not available on this platform")
+    @pytest.mark.skipif(
+        not hasattr(py.path.local, "mksymlinkto"),
+        reason="symlink not available on this platform",
+    )
     def test_chdir(self, testdir):
         testdir.tmpdir.join("py").mksymlinkto(py._pydir)
         p = testdir.tmpdir.join("main.py")
-        p.write(_pytest._code.Source("""
+        p.write(
+            _pytest._code.Source(
+                """
             import sys, os
             sys.path.insert(0, '')
             import py
             print (py.__file__)
             print (py.__path__)
             os.chdir(os.path.dirname(os.getcwd()))
             print (py.log)
-        """))
+        """
+            )
+        )
         result = testdir.runpython(p)
         assert not result.ret
 
     def test_issue109_sibling_conftests_not_loaded(self, testdir):
-        sub1 = testdir.tmpdir.mkdir("sub1")
-        sub2 = testdir.tmpdir.mkdir("sub2")
+        sub1 = testdir.mkdir("sub1")
+        sub2 = testdir.mkdir("sub2")
         sub1.join("conftest.py").write("assert 0")
         result = testdir.runpytest(sub2)
         assert result.ret == EXIT_NOTESTSCOLLECTED
         sub2.ensure("__init__.py")
         p = sub2.ensure("test_hello.py")
         result = testdir.runpytest(p)
         assert result.ret == EXIT_NOTESTSCOLLECTED
         result = testdir.runpytest(sub1)
         assert result.ret == EXIT_USAGEERROR
 
     def test_directory_skipped(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             def pytest_ignore_collect():
                 pytest.skip("intentional")
-        """)
+        """
+        )
         testdir.makepyfile("def test_hello(): pass")
         result = testdir.runpytest()
         assert result.ret == EXIT_NOTESTSCOLLECTED
-        result.stdout.fnmatch_lines([
-            "*1 skipped*"
-        ])
+        result.stdout.fnmatch_lines(["*1 skipped*"])
 
     def test_multiple_items_per_collector_byid(self, testdir):
-        c = testdir.makeconftest("""
+        c = testdir.makeconftest(
+            """
             import pytest
             class MyItem(pytest.Item):
                 def runtest(self):
                     pass
             class MyCollector(pytest.File):
                 def collect(self):
                     return [MyItem(name="xyz", parent=self)]
             def pytest_collect_file(path, parent):
                 if path.basename.startswith("conftest"):
                     return MyCollector(path, parent)
-        """)
+        """
+        )
         result = testdir.runpytest(c.basename + "::" + "xyz")
         assert result.ret == 0
-        result.stdout.fnmatch_lines([
-            "*1 pass*",
-        ])
+        result.stdout.fnmatch_lines(["*1 pass*"])
 
     def test_skip_on_generated_funcarg_id(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             def pytest_generate_tests(metafunc):
                 metafunc.addcall({'x': 3}, id='hello-123')
             def pytest_runtest_setup(item):
                 print (item.keywords)
                 if 'hello-123' in item.keywords:
                     pytest.skip("hello")
                 assert 0
-        """)
+        """
+        )
         p = testdir.makepyfile("""def test_func(x): pass""")
         res = testdir.runpytest(p)
         assert res.ret == 0
         res.stdout.fnmatch_lines(["*1 skipped*"])
 
     def test_direct_addressing_selects(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def pytest_generate_tests(metafunc):
                 metafunc.addcall({'i': 1}, id="1")
                 metafunc.addcall({'i': 2}, id="2")
             def test_func(i):
                 pass
-        """)
+        """
+        )
         res = testdir.runpytest(p.basename + "::" + "test_func[1]")
         assert res.ret == 0
         res.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_direct_addressing_notfound(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_func():
                 pass
-        """)
+        """
+        )
         res = testdir.runpytest(p.basename + "::" + "test_notfound")
         assert res.ret
         res.stderr.fnmatch_lines(["*ERROR*not found*"])
 
     def test_docstring_on_hookspec(self):
         from _pytest import hookspec
+
         for name, value in vars(hookspec).items():
             if name.startswith("pytest_"):
                 assert value.__doc__, "no docstring for %s" % name
 
     def test_initialization_error_issue49(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_configure():
                 x
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == 3  # internal error
-        result.stderr.fnmatch_lines([
-            "INTERNAL*pytest_configure*",
-            "INTERNAL*x*",
-        ])
-        assert 'sessionstarttime' not in result.stderr.str()
+        result.stderr.fnmatch_lines(["INTERNAL*pytest_configure*", "INTERNAL*x*"])
+        assert "sessionstarttime" not in result.stderr.str()
 
-    @pytest.mark.parametrize('lookfor', ['test_fun.py::test_a'])
+    @pytest.mark.parametrize("lookfor", ["test_fun.py::test_a"])
     def test_issue134_report_error_when_collecting_member(self, testdir, lookfor):
-        testdir.makepyfile(test_fun="""
+        testdir.makepyfile(
+            test_fun="""
             def test_a():
                 pass
-            def""")
+            def"""
+        )
         result = testdir.runpytest(lookfor)
-        result.stdout.fnmatch_lines(['*SyntaxError*'])
-        if '::' in lookfor:
-            result.stderr.fnmatch_lines([
-                '*ERROR*',
-            ])
+        result.stdout.fnmatch_lines(["*SyntaxError*"])
+        if "::" in lookfor:
+            result.stderr.fnmatch_lines(["*ERROR*"])
             assert result.ret == 4  # usage error only if item not found
 
     def test_report_all_failed_collections_initargs(self, testdir):
         testdir.makepyfile(test_a="def", test_b="def")
         result = testdir.runpytest("test_a.py::a", "test_b.py::b")
-        result.stderr.fnmatch_lines([
-            "*ERROR*test_a.py::a*",
-            "*ERROR*test_b.py::b*",
-        ])
+        result.stderr.fnmatch_lines(["*ERROR*test_a.py::a*", "*ERROR*test_b.py::b*"])
 
-    @pytest.mark.usefixtures('recwarn')
+    @pytest.mark.usefixtures("recwarn")
     def test_namespace_import_doesnt_confuse_import_hook(self, testdir):
         """
         Ref #383. Python 3.3's namespace package messed with our import hooks
         Importing a module that didn't exist, even if the ImportError was
         gracefully handled, would make our test crash.
 
         Use recwarn here to silence this warning in Python 2.7:
             ImportWarning: Not importing directory '...\not_a_package': missing __init__.py
         """
-        testdir.mkdir('not_a_package')
-        p = testdir.makepyfile("""
+        testdir.mkdir("not_a_package")
+        p = testdir.makepyfile(
+            """
             try:
                 from not_a_package import doesnt_exist
             except ImportError:
                 # We handle the import error gracefully here
                 pass
 
             def test_whatever():
                 pass
-        """)
+        """
+        )
         res = testdir.runpytest(p.basename)
         assert res.ret == 0
 
     def test_unknown_option(self, testdir):
         result = testdir.runpytest("--qwlkej")
-        result.stderr.fnmatch_lines("""
+        result.stderr.fnmatch_lines(
+            """
             *unrecognized*
-        """)
+        """
+        )
 
     def test_getsourcelines_error_issue553(self, testdir, monkeypatch):
         monkeypatch.setattr("inspect.getsourcelines", None)
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def raise_error(obj):
                 raise IOError('source code not available')
 
             import inspect
             inspect.getsourcelines = raise_error
 
             def test_foo(invalid_fixture):
                 pass
-        """)
+        """
+        )
         res = testdir.runpytest(p)
-        res.stdout.fnmatch_lines([
-            "*source code not available*",
-            "E*fixture 'invalid_fixture' not found",
-        ])
+        res.stdout.fnmatch_lines(
+            ["*source code not available*", "E*fixture 'invalid_fixture' not found"]
+        )
 
     def test_plugins_given_as_strings(self, tmpdir, monkeypatch):
         """test that str values passed to main() as `plugins` arg
         are interpreted as module names to be imported and registered.
         #855.
         """
         with pytest.raises(ImportError) as excinfo:
-            pytest.main([str(tmpdir)], plugins=['invalid.module'])
-        assert 'invalid' in str(excinfo.value)
+            pytest.main([str(tmpdir)], plugins=["invalid.module"])
+        assert "invalid" in str(excinfo.value)
 
-        p = tmpdir.join('test_test_plugins_given_as_strings.py')
-        p.write('def test_foo(): pass')
-        mod = py.std.types.ModuleType("myplugin")
-        monkeypatch.setitem(sys.modules, 'myplugin', mod)
-        assert pytest.main(args=[str(tmpdir)], plugins=['myplugin']) == 0
+        p = tmpdir.join("test_test_plugins_given_as_strings.py")
+        p.write("def test_foo(): pass")
+        mod = types.ModuleType("myplugin")
+        monkeypatch.setitem(sys.modules, "myplugin", mod)
+        assert pytest.main(args=[str(tmpdir)], plugins=["myplugin"]) == 0
 
     def test_parametrized_with_bytes_regex(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import re
             import pytest
             @pytest.mark.parametrize('r', [re.compile(b'foo')])
             def test_stuff(r):
                 pass
         """
-                               )
+        )
         res = testdir.runpytest(p)
-        res.stdout.fnmatch_lines([
-            '*1 passed*'
-        ])
+        res.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_parametrized_with_null_bytes(self, testdir):
         """Test parametrization with values that contain null bytes and unicode characters (#2644, #2957)"""
-        p = testdir.makepyfile(u"""
+        p = testdir.makepyfile(
+            u"""
             # encoding: UTF-8
             import pytest
 
             @pytest.mark.parametrize("data", [b"\\x00", "\\x00", u'ação'])
             def test_foo(data):
                 assert data
-        """)
+        """
+        )
         res = testdir.runpytest(p)
         res.assert_outcomes(passed=3)
 
 
 class TestInvocationVariants(object):
+
     def test_earlyinit(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             assert hasattr(pytest, 'mark')
-        """)
+        """
+        )
         result = testdir.runpython(p)
         assert result.ret == 0
 
     @pytest.mark.xfail("sys.platform.startswith('java')")
     def test_pydoc(self, testdir):
-        for name in ('py.test', 'pytest'):
+        for name in ("py.test", "pytest"):
             result = testdir.runpython_c("import %s;help(%s)" % (name, name))
             assert result.ret == 0
             s = result.stdout.str()
-            assert 'MarkGenerator' in s
+            assert "MarkGenerator" in s
 
     def test_import_star_py_dot_test(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             from py.test import *
             #collect
             #cmdline
             #Item
             # assert collect.Item is Item
             # assert collect.Collector is Collector
             main
             skip
             xfail
-        """)
+        """
+        )
         result = testdir.runpython(p)
         assert result.ret == 0
 
     def test_import_star_pytest(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             from pytest import *
             #Item
             #File
             main
             skip
             xfail
-        """)
+        """
+        )
         result = testdir.runpython(p)
         assert result.ret == 0
 
     def test_double_pytestcmdline(self, testdir):
-        p = testdir.makepyfile(run="""
+        p = testdir.makepyfile(
+            run="""
             import pytest
             pytest.main()
             pytest.main()
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             def test_hello():
                 pass
-        """)
+        """
+        )
         result = testdir.runpython(p)
-        result.stdout.fnmatch_lines([
-            "*1 passed*",
-            "*1 passed*",
-        ])
+        result.stdout.fnmatch_lines(["*1 passed*", "*1 passed*"])
 
     def test_python_minus_m_invocation_ok(self, testdir):
         p1 = testdir.makepyfile("def test_hello(): pass")
-        res = testdir.run(py.std.sys.executable, "-m", "pytest", str(p1))
+        res = testdir.run(sys.executable, "-m", "pytest", str(p1))
         assert res.ret == 0
 
     def test_python_minus_m_invocation_fail(self, testdir):
         p1 = testdir.makepyfile("def test_fail(): 0/0")
-        res = testdir.run(py.std.sys.executable, "-m", "pytest", str(p1))
+        res = testdir.run(sys.executable, "-m", "pytest", str(p1))
         assert res.ret == 1
 
     def test_python_pytest_package(self, testdir):
         p1 = testdir.makepyfile("def test_pass(): pass")
-        res = testdir.run(py.std.sys.executable, "-m", "pytest", str(p1))
+        res = testdir.run(sys.executable, "-m", "pytest", str(p1))
         assert res.ret == 0
         res.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_equivalence_pytest_pytest(self):
         assert pytest.main == py.test.cmdline.main
 
     def test_invoke_with_string(self, capsys):
         retcode = pytest.main("-h")
@@ -515,188 +552,264 @@ class TestInvocationVariants(object):
         pytest.raises(ValueError, lambda: pytest.main(0))
 
     def test_invoke_with_path(self, tmpdir, capsys):
         retcode = pytest.main(tmpdir)
         assert retcode == EXIT_NOTESTSCOLLECTED
         out, err = capsys.readouterr()
 
     def test_invoke_plugin_api(self, testdir, capsys):
+
         class MyPlugin(object):
+
             def pytest_addoption(self, parser):
                 parser.addoption("--myopt")
 
         pytest.main(["-h"], plugins=[MyPlugin()])
         out, err = capsys.readouterr()
         assert "--myopt" in out
 
     def test_pyargs_importerror(self, testdir, monkeypatch):
-        monkeypatch.delenv('PYTHONDONTWRITEBYTECODE', False)
+        monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", False)
         path = testdir.mkpydir("tpkg")
-        path.join("test_hello.py").write('raise ImportError')
+        path.join("test_hello.py").write("raise ImportError")
 
-        result = testdir.runpytest_subprocess("--pyargs", "tpkg.test_hello")
+        result = testdir.runpytest("--pyargs", "tpkg.test_hello", syspathinsert=True)
         assert result.ret != 0
 
-        result.stdout.fnmatch_lines([
-            "collected*0*items*/*1*errors"
-        ])
+        result.stdout.fnmatch_lines(["collected*0*items*/*1*errors"])
 
     def test_cmdline_python_package(self, testdir, monkeypatch):
         import warnings
-        monkeypatch.delenv('PYTHONDONTWRITEBYTECODE', False)
+
+        monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", False)
         path = testdir.mkpydir("tpkg")
         path.join("test_hello.py").write("def test_hello(): pass")
         path.join("test_world.py").write("def test_world(): pass")
         result = testdir.runpytest("--pyargs", "tpkg")
         assert result.ret == 0
-        result.stdout.fnmatch_lines([
-            "*2 passed*"
-        ])
-        result = testdir.runpytest("--pyargs", "tpkg.test_hello")
+        result.stdout.fnmatch_lines(["*2 passed*"])
+        result = testdir.runpytest("--pyargs", "tpkg.test_hello", syspathinsert=True)
         assert result.ret == 0
-        result.stdout.fnmatch_lines([
-            "*1 passed*"
-        ])
+        result.stdout.fnmatch_lines(["*1 passed*"])
 
         def join_pythonpath(what):
-            cur = py.std.os.environ.get('PYTHONPATH')
+            cur = os.environ.get("PYTHONPATH")
             if cur:
                 return str(what) + os.pathsep + cur
             return what
+
         empty_package = testdir.mkpydir("empty_package")
-        monkeypatch.setenv('PYTHONPATH', join_pythonpath(empty_package))
+        monkeypatch.setenv("PYTHONPATH", join_pythonpath(empty_package))
         # the path which is not a package raises a warning on pypy;
         # no idea why only pypy and not normal python warn about it here
         with warnings.catch_warnings():
-            warnings.simplefilter('ignore', ImportWarning)
+            warnings.simplefilter("ignore", ImportWarning)
             result = testdir.runpytest("--pyargs", ".")
         assert result.ret == 0
-        result.stdout.fnmatch_lines([
-            "*2 passed*"
-        ])
+        result.stdout.fnmatch_lines(["*2 passed*"])
 
-        monkeypatch.setenv('PYTHONPATH', join_pythonpath(testdir))
-        result = testdir.runpytest("--pyargs", "tpkg.test_missing")
+        monkeypatch.setenv("PYTHONPATH", join_pythonpath(testdir))
+        result = testdir.runpytest("--pyargs", "tpkg.test_missing", syspathinsert=True)
         assert result.ret != 0
-        result.stderr.fnmatch_lines([
-            "*not*found*test_missing*",
-        ])
+        result.stderr.fnmatch_lines(["*not*found*test_missing*"])
 
     def test_cmdline_python_namespace_package(self, testdir, monkeypatch):
         """
         test --pyargs option with namespace packages (#1567)
         """
-        monkeypatch.delenv('PYTHONDONTWRITEBYTECODE', raising=False)
+        monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
 
         search_path = []
         for dirname in "hello", "world":
             d = testdir.mkdir(dirname)
             search_path.append(d)
             ns = d.mkdir("ns_pkg")
             ns.join("__init__.py").write(
-                "__import__('pkg_resources').declare_namespace(__name__)")
+                "__import__('pkg_resources').declare_namespace(__name__)"
+            )
             lib = ns.mkdir(dirname)
             lib.ensure("__init__.py")
-            lib.join("test_{0}.py".format(dirname)). \
-                write("def test_{0}(): pass\n"
-                      "def test_other():pass".format(dirname))
+            lib.join("test_{}.py".format(dirname)).write(
+                "def test_{}(): pass\n" "def test_other():pass".format(dirname)
+            )
 
         # The structure of the test directory is now:
         # .
         # ├── hello
-        # │   └── ns_pkg
-        # │       ├── __init__.py
-        # │       └── hello
-        # │           ├── __init__.py
-        # │           └── test_hello.py
+        # │   └── ns_pkg
+        # │       ├── __init__.py
+        # │       └── hello
+        # │           ├── __init__.py
+        # │           └── test_hello.py
         # └── world
         #     └── ns_pkg
         #         ├── __init__.py
         #         └── world
         #             ├── __init__.py
         #             └── test_world.py
 
         def join_pythonpath(*dirs):
-            cur = py.std.os.environ.get('PYTHONPATH')
+            cur = os.environ.get("PYTHONPATH")
             if cur:
                 dirs += (cur,)
             return os.pathsep.join(str(p) for p in dirs)
-        monkeypatch.setenv('PYTHONPATH', join_pythonpath(*search_path))
+
+        monkeypatch.setenv("PYTHONPATH", join_pythonpath(*search_path))
         for p in search_path:
             monkeypatch.syspath_prepend(p)
 
-        os.chdir('world')
         # mixed module and filenames:
+        os.chdir("world")
         result = testdir.runpytest("--pyargs", "-v", "ns_pkg.hello", "ns_pkg/world")
+        assert result.ret == 0
+        result.stdout.fnmatch_lines(
+            [
+                "*test_hello.py::test_hello*PASSED*",
+                "*test_hello.py::test_other*PASSED*",
+                "*test_world.py::test_world*PASSED*",
+                "*test_world.py::test_other*PASSED*",
+                "*4 passed*",
+            ]
+        )
+
+        # specify tests within a module
+        testdir.chdir()
+        result = testdir.runpytest(
+            "--pyargs", "-v", "ns_pkg.world.test_world::test_other"
+        )
+        assert result.ret == 0
+        result.stdout.fnmatch_lines(
+            ["*test_world.py::test_other*PASSED*", "*1 passed*"]
+        )
+
+    @pytest.mark.skipif(not hasattr(os, "symlink"), reason="requires symlinks")
+    def test_cmdline_python_package_symlink(self, testdir, monkeypatch):
+        """
+        test --pyargs option with packages with path containing symlink can
+        have conftest.py in their package (#2985)
+        """
+        # dummy check that we can actually create symlinks: on Windows `os.symlink` is available,
+        # but normal users require special admin privileges to create symlinks.
+        if sys.platform == "win32":
+            try:
+                os.symlink(
+                    str(testdir.tmpdir.ensure("tmpfile")),
+                    str(testdir.tmpdir.join("tmpfile2")),
+                )
+            except OSError as e:
+                pytest.skip(six.text_type(e.args[0]))
+        monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
+
+        search_path = ["lib", os.path.join("local", "lib")]
+
+        dirname = "lib"
+        d = testdir.mkdir(dirname)
+        foo = d.mkdir("foo")
+        foo.ensure("__init__.py")
+        lib = foo.mkdir("bar")
+        lib.ensure("__init__.py")
+        lib.join("test_bar.py").write(
+            "def test_bar(): pass\n" "def test_other(a_fixture):pass"
+        )
+        lib.join("conftest.py").write(
+            "import pytest\n" "@pytest.fixture\n" "def a_fixture():pass"
+        )
+
+        d_local = testdir.mkdir("local")
+        symlink_location = os.path.join(str(d_local), "lib")
+        if six.PY2:
+            os.symlink(str(d), symlink_location)
+        else:
+            os.symlink(str(d), symlink_location, target_is_directory=True)
+
+        # The structure of the test directory is now:
+        # .
+        # ├── local
+        # │   └── lib -> ../lib
+        # └── lib
+        #     └── foo
+        #         ├── __init__.py
+        #         └── bar
+        #             ├── __init__.py
+        #             ├── conftest.py
+        #             └── test_bar.py
+
+        def join_pythonpath(*dirs):
+            cur = os.getenv("PYTHONPATH")
+            if cur:
+                dirs += (cur,)
+            return os.pathsep.join(str(p) for p in dirs)
+
+        monkeypatch.setenv("PYTHONPATH", join_pythonpath(*search_path))
+        for p in search_path:
+            monkeypatch.syspath_prepend(p)
+
+        # module picked up in symlink-ed directory:
+        result = testdir.runpytest("--pyargs", "-v", "foo.bar")
         testdir.chdir()
         assert result.ret == 0
-        result.stdout.fnmatch_lines([
-            "*test_hello.py::test_hello*PASSED*",
-            "*test_hello.py::test_other*PASSED*",
-            "*test_world.py::test_world*PASSED*",
-            "*test_world.py::test_other*PASSED*",
-            "*4 passed*"
-        ])
-
-        # specify tests within a module
-        result = testdir.runpytest("--pyargs", "-v", "ns_pkg.world.test_world::test_other")
-        assert result.ret == 0
-        result.stdout.fnmatch_lines([
-            "*test_world.py::test_other*PASSED*",
-            "*1 passed*"
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*lib/foo/bar/test_bar.py::test_bar*PASSED*",
+                "*lib/foo/bar/test_bar.py::test_other*PASSED*",
+                "*2 passed*",
+            ]
+        )
 
     def test_cmdline_python_package_not_exists(self, testdir):
         result = testdir.runpytest("--pyargs", "tpkgwhatv")
         assert result.ret
-        result.stderr.fnmatch_lines([
-            "ERROR*file*or*package*not*found*",
-        ])
+        result.stderr.fnmatch_lines(["ERROR*file*or*package*not*found*"])
 
     @pytest.mark.xfail(reason="decide: feature or bug")
     def test_noclass_discovery_if_not_testcase(self, testdir):
-        testpath = testdir.makepyfile("""
+        testpath = testdir.makepyfile(
+            """
             import unittest
             class TestHello(object):
                 def test_hello(self):
                     assert self.attr
 
             class RealTest(unittest.TestCase, TestHello):
                 attr = 42
-        """)
+        """
+        )
         reprec = testdir.inline_run(testpath)
         reprec.assertoutcome(passed=1)
 
     def test_doctest_id(self, testdir):
-        testdir.makefile('.txt', """
+        testdir.makefile(
+            ".txt",
+            """
             >>> x=3
             >>> x
             4
-        """)
+        """,
+        )
         result = testdir.runpytest("-rf")
         lines = result.stdout.str().splitlines()
         for line in lines:
             if line.startswith("FAIL "):
                 testid = line[5:].strip()
                 break
-        result = testdir.runpytest(testid, '-rf')
-        result.stdout.fnmatch_lines([
-            line,
-            "*1 failed*",
-        ])
+        result = testdir.runpytest(testid, "-rf")
+        result.stdout.fnmatch_lines([line, "*1 failed*"])
 
     def test_core_backward_compatibility(self):
         """Test backward compatibility for get_plugin_manager function. See #787."""
         import _pytest.config
-        assert type(_pytest.config.get_plugin_manager()) is _pytest.config.PytestPluginManager
+
+        assert type(
+            _pytest.config.get_plugin_manager()
+        ) is _pytest.config.PytestPluginManager
 
     def test_has_plugin(self, request):
         """Test hasplugin function of the plugin manager (#932)."""
-        assert request.config.pluginmanager.hasplugin('python')
+        assert request.config.pluginmanager.hasplugin("python")
 
 
 class TestDurations(object):
     source = """
         import time
         frag = 0.002
         def test_something():
             pass
@@ -707,59 +820,51 @@ class TestDurations(object):
         def test_3():
             time.sleep(frag*10)
     """
 
     def test_calls(self, testdir):
         testdir.makepyfile(self.source)
         result = testdir.runpytest("--durations=10")
         assert result.ret == 0
-        result.stdout.fnmatch_lines_random([
-            "*durations*",
-            "*call*test_3*",
-            "*call*test_2*",
-            "*call*test_1*",
-        ])
+        result.stdout.fnmatch_lines_random(
+            ["*durations*", "*call*test_3*", "*call*test_2*", "*call*test_1*"]
+        )
 
     def test_calls_show_2(self, testdir):
         testdir.makepyfile(self.source)
         result = testdir.runpytest("--durations=2")
         assert result.ret == 0
         lines = result.stdout.get_lines_after("*slowest*durations*")
         assert "4 passed" in lines[2]
 
     def test_calls_showall(self, testdir):
         testdir.makepyfile(self.source)
         result = testdir.runpytest("--durations=0")
         assert result.ret == 0
         for x in "123":
-            for y in 'call', :  # 'setup', 'call', 'teardown':
+            for y in ("call",):  # 'setup', 'call', 'teardown':
                 for line in result.stdout.lines:
                     if ("test_%s" % x) in line and y in line:
                         break
                 else:
                     raise AssertionError("not found %s %s" % (x, y))
 
     def test_with_deselected(self, testdir):
         testdir.makepyfile(self.source)
         result = testdir.runpytest("--durations=2", "-k test_1")
         assert result.ret == 0
-        result.stdout.fnmatch_lines([
-            "*durations*",
-            "*call*test_1*",
-        ])
+        result.stdout.fnmatch_lines(["*durations*", "*call*test_1*"])
 
     def test_with_failing_collection(self, testdir):
         testdir.makepyfile(self.source)
         testdir.makepyfile(test_collecterror="""xyz""")
         result = testdir.runpytest("--durations=2", "-k test_1")
         assert result.ret == 2
-        result.stdout.fnmatch_lines([
-            "*Interrupted: 1 errors during collection*",
-        ])
+        result.stdout.fnmatch_lines(["*Interrupted: 1 errors during collection*"])
         # Collection errors abort test execution, therefore no duration is
         # output
         assert "duration" not in result.stdout.str()
 
     def test_with_not(self, testdir):
         testdir.makepyfile(self.source)
         result = testdir.runpytest("-k not 1")
         assert result.ret == 0
@@ -777,74 +882,185 @@ class TestDurationWithFixture(object):
             time.sleep(frag)
     """
 
     def test_setup_function(self, testdir):
         testdir.makepyfile(self.source)
         result = testdir.runpytest("--durations=10")
         assert result.ret == 0
 
-        result.stdout.fnmatch_lines_random("""
+        result.stdout.fnmatch_lines_random(
+            """
             *durations*
             * setup *test_1*
             * call *test_1*
-        """)
+        """
+        )
 
 
 def test_zipimport_hook(testdir, tmpdir):
     """Test package loader is being used correctly (see #1837)."""
-    zipapp = pytest.importorskip('zipapp')
-    testdir.tmpdir.join('app').ensure(dir=1)
-    testdir.makepyfile(**{
-        'app/foo.py': """
+    zipapp = pytest.importorskip("zipapp")
+    testdir.tmpdir.join("app").ensure(dir=1)
+    testdir.makepyfile(
+        **{
+            "app/foo.py": """
             import pytest
             def main():
                 pytest.main(['--pyarg', 'foo'])
-        """,
-    })
-    target = tmpdir.join('foo.zip')
-    zipapp.create_archive(str(testdir.tmpdir.join('app')), str(target), main='foo:main')
+        """
+        }
+    )
+    target = tmpdir.join("foo.zip")
+    zipapp.create_archive(str(testdir.tmpdir.join("app")), str(target), main="foo:main")
     result = testdir.runpython(target)
     assert result.ret == 0
-    result.stderr.fnmatch_lines(['*not found*foo*'])
-    assert 'INTERNALERROR>' not in result.stdout.str()
+    result.stderr.fnmatch_lines(["*not found*foo*"])
+    assert "INTERNALERROR>" not in result.stdout.str()
 
 
 def test_import_plugin_unicode_name(testdir):
+    testdir.makepyfile(myplugin="")
     testdir.makepyfile(
-        myplugin='',
-    )
-    testdir.makepyfile("""
+        """
         def test(): pass
-    """)
-    testdir.makeconftest("""
+    """
+    )
+    testdir.makeconftest(
+        """
         pytest_plugins = [u'myplugin']
-    """)
+    """
+    )
     r = testdir.runpytest()
     assert r.ret == 0
 
 
 def test_deferred_hook_checking(testdir):
     """
     Check hooks as late as possible (#1821).
     """
     testdir.syspathinsert()
-    testdir.makepyfile(**{
-        'plugin.py': """
-        class Hooks:
+    testdir.makepyfile(
+        **{
+            "plugin.py": """
+        class Hooks(object):
             def pytest_my_hook(self, config):
                 pass
 
         def pytest_configure(config):
             config.pluginmanager.add_hookspecs(Hooks)
         """,
-        'conftest.py': """
+            "conftest.py": """
             pytest_plugins = ['plugin']
             def pytest_my_hook(config):
                 return 40
         """,
-        'test_foo.py': """
+            "test_foo.py": """
             def test(request):
                 assert request.config.hook.pytest_my_hook(config=request.config) == [40]
+        """,
+        }
+    )
+    result = testdir.runpytest()
+    result.stdout.fnmatch_lines(["* 1 passed *"])
+
+
+def test_fixture_values_leak(testdir):
+    """Ensure that fixture objects are properly destroyed by the garbage collector at the end of their expected
+    life-times (#2981).
+    """
+    testdir.makepyfile(
         """
-    })
+        import attr
+        import gc
+        import pytest
+        import weakref
+
+        @attr.s
+        class SomeObj(object):
+            name = attr.ib()
+
+        fix_of_test1_ref = None
+        session_ref = None
+
+        @pytest.fixture(scope='session')
+        def session_fix():
+            global session_ref
+            obj = SomeObj(name='session-fixture')
+            session_ref = weakref.ref(obj)
+            return obj
+
+        @pytest.fixture
+        def fix(session_fix):
+            global fix_of_test1_ref
+            obj = SomeObj(name='local-fixture')
+            fix_of_test1_ref = weakref.ref(obj)
+            return obj
+
+        def test1(fix):
+            assert fix_of_test1_ref() is fix
+
+        def test2():
+            gc.collect()
+            # fixture "fix" created during test1 must have been destroyed by now
+            assert fix_of_test1_ref() is None
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines(['* 1 passed *'])
+    result.stdout.fnmatch_lines(["* 2 passed *"])
+
+
+def test_fixture_order_respects_scope(testdir):
+    """Ensure that fixtures are created according to scope order, regression test for #2405
+    """
+    testdir.makepyfile(
+        """
+        import pytest
+
+        data = {}
+
+        @pytest.fixture(scope='module')
+        def clean_data():
+            data.clear()
+
+        @pytest.fixture(autouse=True)
+        def add_data():
+            data.update(value=True)
+
+        @pytest.mark.usefixtures('clean_data')
+        def test_value():
+            assert data.get('value')
+    """
+    )
+    result = testdir.runpytest()
+    assert result.ret == 0
+
+
+def test_frame_leak_on_failing_test(testdir):
+    """pytest would leak garbage referencing the frames of tests that failed that could never be reclaimed (#2798)
+
+    Unfortunately it was not possible to remove the actual circles because most of them
+    are made of traceback objects which cannot be weakly referenced. Those objects at least
+    can be eventually claimed by the garbage collector.
+    """
+    testdir.makepyfile(
+        """
+        import gc
+        import weakref
+
+        class Obj:
+            pass
+
+        ref = None
+
+        def test1():
+            obj = Obj()
+            global ref
+            ref = weakref.ref(obj)
+            assert 0
+
+        def test2():
+            gc.collect()
+            assert ref() is None
+    """
+    )
+    result = testdir.runpytest_subprocess()
+    result.stdout.fnmatch_lines(["*1 failed, 1 passed in*"])
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/code/test_code.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/code/test_code.py
@@ -1,71 +1,79 @@
 # coding: utf-8
 from __future__ import absolute_import, division, print_function
 import sys
 
 import _pytest._code
 import py
 import pytest
 from test_excinfo import TWMock
+from six import text_type
 
 
 def test_ne():
-    code1 = _pytest._code.Code(compile('foo = "bar"', '', 'exec'))
+    code1 = _pytest._code.Code(compile('foo = "bar"', "", "exec"))
     assert code1 == code1
-    code2 = _pytest._code.Code(compile('foo = "baz"', '', 'exec'))
+    code2 = _pytest._code.Code(compile('foo = "baz"', "", "exec"))
     assert code2 != code1
 
 
 def test_code_gives_back_name_for_not_existing_file():
-    name = 'abc-123'
-    co_code = compile("pass\n", name, 'exec')
+    name = "abc-123"
+    co_code = compile("pass\n", name, "exec")
     assert co_code.co_filename == name
     code = _pytest._code.Code(co_code)
     assert str(code.path) == name
     assert code.fullsource is None
 
 
 def test_code_with_class():
+
     class A(object):
         pass
+
     pytest.raises(TypeError, "_pytest._code.Code(A)")
 
 
 if True:
+
     def x():
         pass
 
 
 def test_code_fullsource():
     code = _pytest._code.Code(x)
     full = code.fullsource
-    assert 'test_code_fullsource()' in str(full)
+    assert "test_code_fullsource()" in str(full)
 
 
 def test_code_source():
     code = _pytest._code.Code(x)
     src = code.source()
     expected = """def x():
     pass"""
     assert str(src) == expected
 
 
 def test_frame_getsourcelineno_myself():
+
     def func():
         return sys._getframe(0)
+
     f = func()
     f = _pytest._code.Frame(f)
     source, lineno = f.code.fullsource, f.lineno
     assert source[lineno].startswith("        return sys._getframe(0)")
 
 
 def test_getstatement_empty_fullsource():
+
     def func():
         return sys._getframe(0)
+
     f = func()
     f = _pytest._code.Frame(f)
     prop = f.code.__class__.fullsource
     try:
         f.code.__class__.fullsource = None
         assert f.statement == _pytest._code.Source("")
     finally:
         f.code.__class__.fullsource = prop
@@ -73,83 +81,92 @@ def test_getstatement_empty_fullsource()
 
 def test_code_from_func():
     co = _pytest._code.Code(test_frame_getsourcelineno_myself)
     assert co.firstlineno
     assert co.path
 
 
 def test_unicode_handling():
-    value = py.builtin._totext('\xc4\x85\xc4\x87\n', 'utf-8').encode('utf8')
+    value = py.builtin._totext("\xc4\x85\xc4\x87\n", "utf-8").encode("utf8")
 
     def f():
         raise Exception(value)
 
     excinfo = pytest.raises(Exception, f)
     str(excinfo)
     if sys.version_info[0] < 3:
-        unicode(excinfo)
+        text_type(excinfo)
 
 
-@pytest.mark.skipif(sys.version_info[0] >= 3, reason='python 2 only issue')
+@pytest.mark.skipif(sys.version_info[0] >= 3, reason="python 2 only issue")
 def test_unicode_handling_syntax_error():
-    value = py.builtin._totext('\xc4\x85\xc4\x87\n', 'utf-8').encode('utf8')
+    value = py.builtin._totext("\xc4\x85\xc4\x87\n", "utf-8").encode("utf8")
 
     def f():
-        raise SyntaxError('invalid syntax', (None, 1, 3, value))
+        raise SyntaxError("invalid syntax", (None, 1, 3, value))
 
     excinfo = pytest.raises(Exception, f)
     str(excinfo)
     if sys.version_info[0] < 3:
-        unicode(excinfo)
+        text_type(excinfo)
 
 
 def test_code_getargs():
+
     def f1(x):
         pass
+
     c1 = _pytest._code.Code(f1)
-    assert c1.getargs(var=True) == ('x',)
+    assert c1.getargs(var=True) == ("x",)
 
     def f2(x, *y):
         pass
+
     c2 = _pytest._code.Code(f2)
-    assert c2.getargs(var=True) == ('x', 'y')
+    assert c2.getargs(var=True) == ("x", "y")
 
     def f3(x, **z):
         pass
+
     c3 = _pytest._code.Code(f3)
-    assert c3.getargs(var=True) == ('x', 'z')
+    assert c3.getargs(var=True) == ("x", "z")
 
     def f4(x, *y, **z):
         pass
+
     c4 = _pytest._code.Code(f4)
-    assert c4.getargs(var=True) == ('x', 'y', 'z')
+    assert c4.getargs(var=True) == ("x", "y", "z")
 
 
 def test_frame_getargs():
+
     def f1(x):
         return sys._getframe(0)
-    fr1 = _pytest._code.Frame(f1('a'))
-    assert fr1.getargs(var=True) == [('x', 'a')]
+
+    fr1 = _pytest._code.Frame(f1("a"))
+    assert fr1.getargs(var=True) == [("x", "a")]
 
     def f2(x, *y):
         return sys._getframe(0)
-    fr2 = _pytest._code.Frame(f2('a', 'b', 'c'))
-    assert fr2.getargs(var=True) == [('x', 'a'), ('y', ('b', 'c'))]
+
+    fr2 = _pytest._code.Frame(f2("a", "b", "c"))
+    assert fr2.getargs(var=True) == [("x", "a"), ("y", ("b", "c"))]
 
     def f3(x, **z):
         return sys._getframe(0)
-    fr3 = _pytest._code.Frame(f3('a', b='c'))
-    assert fr3.getargs(var=True) == [('x', 'a'), ('z', {'b': 'c'})]
+
+    fr3 = _pytest._code.Frame(f3("a", b="c"))
+    assert fr3.getargs(var=True) == [("x", "a"), ("z", {"b": "c"})]
 
     def f4(x, *y, **z):
         return sys._getframe(0)
-    fr4 = _pytest._code.Frame(f4('a', 'b', c='d'))
-    assert fr4.getargs(var=True) == [('x', 'a'), ('y', ('b',)),
-                                     ('z', {'c': 'd'})]
+
+    fr4 = _pytest._code.Frame(f4("a", "b", c="d"))
+    assert fr4.getargs(var=True) == [("x", "a"), ("y", ("b",)), ("z", {"c": "d"})]
 
 
 class TestExceptionInfo(object):
 
     def test_bad_getsource(self):
         try:
             if False:
                 pass
@@ -168,29 +185,26 @@ class TestTracebackEntry(object):
                 pass
             else:
                 assert False
         except AssertionError:
             exci = _pytest._code.ExceptionInfo()
         entry = exci.traceback[0]
         source = entry.getsource()
         assert len(source) == 6
-        assert 'assert False' in source[5]
+        assert "assert False" in source[5]
 
 
 class TestReprFuncArgs(object):
 
     def test_not_raise_exception_with_mixed_encoding(self):
         from _pytest._code.code import ReprFuncArgs
 
         tw = TWMock()
 
-        args = [
-            ('unicode_string', u"São Paulo"),
-            ('utf8_string', 'S\xc3\xa3o Paulo'),
-        ]
+        args = [("unicode_string", u"São Paulo"), ("utf8_string", "S\xc3\xa3o Paulo")]
 
         r = ReprFuncArgs(args)
         r.toterminal(tw)
         if sys.version_info[0] >= 3:
-            assert tw.lines[0] == 'unicode_string = São Paulo, utf8_string = São Paulo'
+            assert tw.lines[0] == "unicode_string = São Paulo, utf8_string = São Paulo"
         else:
-            assert tw.lines[0] == 'unicode_string = São Paulo, utf8_string = São Paulo'
+            assert tw.lines[0] == "unicode_string = São Paulo, utf8_string = São Paulo"
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/code/test_excinfo.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/code/test_excinfo.py
@@ -1,32 +1,34 @@
 # -*- coding: utf-8 -*-
 from __future__ import absolute_import, division, print_function
 
 import operator
+import os
+import sys
 import _pytest
 import py
 import pytest
 from _pytest._code.code import (
     ExceptionInfo,
     FormattedExcinfo,
     ReprExceptionInfo,
-    ExceptionChainRepr)
+    ExceptionChainRepr,
+)
+from six.moves import queue
 
 from test_source import astonly
 
 try:
     import importlib
 except ImportError:
     invalidate_import_caches = None
 else:
     invalidate_import_caches = getattr(importlib, "invalidate_caches", None)
 
-queue = py.builtin._tryimport('queue', 'Queue')
-
 failsonjython = pytest.mark.xfail("sys.platform.startswith('java')")
 
 pytest_version_info = tuple(map(int, pytest.__version__.split(".")[:3]))
 
 
 class TWMock(object):
     WRITE = object()
 
@@ -58,36 +60,40 @@ def test_excinfo_simple():
     try:
         raise ValueError
     except ValueError:
         info = _pytest._code.ExceptionInfo()
     assert info.type == ValueError
 
 
 def test_excinfo_getstatement():
+
     def g():
         raise ValueError
 
     def f():
         g()
 
     try:
         f()
     except ValueError:
         excinfo = _pytest._code.ExceptionInfo()
-    linenumbers = [_pytest._code.getrawcode(f).co_firstlineno - 1 + 4,
-                   _pytest._code.getrawcode(f).co_firstlineno - 1 + 1,
-                   _pytest._code.getrawcode(g).co_firstlineno - 1 + 1, ]
+    linenumbers = [
+        _pytest._code.getrawcode(f).co_firstlineno - 1 + 4,
+        _pytest._code.getrawcode(f).co_firstlineno - 1 + 1,
+        _pytest._code.getrawcode(g).co_firstlineno - 1 + 1,
+    ]
     values = list(excinfo.traceback)
     foundlinenumbers = [x.lineno for x in values]
     assert foundlinenumbers == linenumbers
     # for x in info:
     #    print "%s:%d  %s" %(x.path.relto(root), x.lineno, x.statement)
     # xxx
 
+
 # testchain for getentries test below
 
 
 def f():
     #
     raise ValueError
     #
 
@@ -101,52 +107,55 @@ def g():
 
 def h():
     #
     g()
     #
 
 
 class TestTraceback_f_g_h(object):
+
     def setup_method(self, method):
         try:
             h()
         except ValueError:
             self.excinfo = _pytest._code.ExceptionInfo()
 
     def test_traceback_entries(self):
         tb = self.excinfo.traceback
         entries = list(tb)
         assert len(tb) == 4  # maybe fragile test
         assert len(entries) == 4  # maybe fragile test
-        names = ['f', 'g', 'h']
+        names = ["f", "g", "h"]
         for entry in entries:
             try:
                 names.remove(entry.frame.code.name)
             except ValueError:
                 pass
         assert not names
 
     def test_traceback_entry_getsource(self):
         tb = self.excinfo.traceback
         s = str(tb[-1].getsource())
         assert s.startswith("def f():")
         assert s.endswith("raise ValueError")
 
     @astonly
     @failsonjython
     def test_traceback_entry_getsource_in_construct(self):
-        source = _pytest._code.Source("""\
+        source = _pytest._code.Source(
+            """\
             def xyz():
                 try:
                     raise ValueError
                 except somenoname:
                     pass
             xyz()
-        """)
+        """
+        )
         try:
             exec(source.compile())
         except NameError:
             tb = _pytest._code.ExceptionInfo().traceback
             print(tb[-1].getsource())
             s = str(tb[-1].getsource())
             assert s.startswith("def xyz():\n    try:")
             assert s.strip().endswith("except somenoname:")
@@ -161,32 +170,36 @@ class TestTraceback_f_g_h(object):
         assert len(newtraceback) == 1
 
     def test_traceback_cut_excludepath(self, testdir):
         p = testdir.makepyfile("def f(): raise ValueError")
         excinfo = pytest.raises(ValueError, "p.pyimport().f()")
         basedir = py.path.local(pytest.__file__).dirpath()
         newtraceback = excinfo.traceback.cut(excludepath=basedir)
         for x in newtraceback:
-            if hasattr(x, 'path'):
+            if hasattr(x, "path"):
                 assert not py.path.local(x.path).relto(basedir)
         assert newtraceback[-1].frame.code.path == p
 
     def test_traceback_filter(self):
         traceback = self.excinfo.traceback
         ntraceback = traceback.filter()
         assert len(ntraceback) == len(traceback) - 1
 
-    @pytest.mark.parametrize('tracebackhide, matching', [
-        (lambda info: True, True),
-        (lambda info: False, False),
-        (operator.methodcaller('errisinstance', ValueError), True),
-        (operator.methodcaller('errisinstance', IndexError), False),
-    ])
+    @pytest.mark.parametrize(
+        "tracebackhide, matching",
+        [
+            (lambda info: True, True),
+            (lambda info: False, False),
+            (operator.methodcaller("errisinstance", ValueError), True),
+            (operator.methodcaller("errisinstance", IndexError), False),
+        ],
+    )
     def test_traceback_filter_selective(self, tracebackhide, matching):
+
         def f():
             #
             raise ValueError
             #
 
         def g():
             #
             __tracebackhide__ = tracebackhide
@@ -196,84 +209,91 @@ class TestTraceback_f_g_h(object):
         def h():
             #
             g()
             #
 
         excinfo = pytest.raises(ValueError, h)
         traceback = excinfo.traceback
         ntraceback = traceback.filter()
-        print('old: {0!r}'.format(traceback))
-        print('new: {0!r}'.format(ntraceback))
+        print("old: {!r}".format(traceback))
+        print("new: {!r}".format(ntraceback))
 
         if matching:
             assert len(ntraceback) == len(traceback) - 2
         else:
             # -1 because of the __tracebackhide__ in pytest.raises
             assert len(ntraceback) == len(traceback) - 1
 
     def test_traceback_recursion_index(self):
+
         def f(n):
             if n < 10:
                 n += 1
             f(n)
+
         excinfo = pytest.raises(RuntimeError, f, 8)
         traceback = excinfo.traceback
         recindex = traceback.recursionindex()
         assert recindex == 3
 
     def test_traceback_only_specific_recursion_errors(self, monkeypatch):
+
         def f(n):
             if n == 0:
                 raise RuntimeError("hello")
             f(n - 1)
 
         excinfo = pytest.raises(RuntimeError, f, 100)
         monkeypatch.delattr(excinfo.traceback.__class__, "recursionindex")
         repr = excinfo.getrepr()
         assert "RuntimeError: hello" in str(repr.reprcrash)
 
     def test_traceback_no_recursion_index(self):
+
         def do_stuff():
             raise RuntimeError
 
         def reraise_me():
             import sys
+
             exc, val, tb = sys.exc_info()
             py.builtin._reraise(exc, val, tb)
 
         def f(n):
             try:
                 do_stuff()
             except:  # noqa
                 reraise_me()
 
         excinfo = pytest.raises(RuntimeError, f, 8)
         traceback = excinfo.traceback
         recindex = traceback.recursionindex()
         assert recindex is None
 
     def test_traceback_messy_recursion(self):
         # XXX: simplified locally testable version
-        decorator = pytest.importorskip('decorator').decorator
+        decorator = pytest.importorskip("decorator").decorator
 
         def log(f, *k, **kw):
-            print('%s %s' % (k, kw))
+            print("%s %s" % (k, kw))
             f(*k, **kw)
+
         log = decorator(log)
 
         def fail():
-            raise ValueError('')
+            raise ValueError("")
 
         fail = log(log(fail))
 
         excinfo = pytest.raises(ValueError, fail)
         assert excinfo.traceback.recursionindex() is None
 
     def test_traceback_getcrashentry(self):
+
         def i():
             __tracebackhide__ = True
             raise ValueError
 
         def h():
             i()
 
         def g():
@@ -284,43 +304,43 @@ class TestTraceback_f_g_h(object):
             g()
 
         excinfo = pytest.raises(ValueError, f)
         tb = excinfo.traceback
         entry = tb.getcrashentry()
         co = _pytest._code.Code(h)
         assert entry.frame.code.path == co.path
         assert entry.lineno == co.firstlineno + 1
-        assert entry.frame.code.name == 'h'
+        assert entry.frame.code.name == "h"
 
     def test_traceback_getcrashentry_empty(self):
+
         def g():
             __tracebackhide__ = True
             raise ValueError
 
         def f():
             __tracebackhide__ = True
             g()
 
         excinfo = pytest.raises(ValueError, f)
         tb = excinfo.traceback
         entry = tb.getcrashentry()
         co = _pytest._code.Code(g)
         assert entry.frame.code.path == co.path
         assert entry.lineno == co.firstlineno + 2
-        assert entry.frame.code.name == 'g'
+        assert entry.frame.code.name == "g"
 
 
 def test_excinfo_exconly():
     excinfo = pytest.raises(ValueError, h)
-    assert excinfo.exconly().startswith('ValueError')
-    excinfo = pytest.raises(ValueError,
-                            "raise ValueError('hello\\nworld')")
+    assert excinfo.exconly().startswith("ValueError")
+    excinfo = pytest.raises(ValueError, "raise ValueError('hello\\nworld')")
     msg = excinfo.exconly(tryshort=True)
-    assert msg.startswith('ValueError')
+    assert msg.startswith("ValueError")
     assert msg.endswith("world")
 
 
 def test_excinfo_repr():
     excinfo = pytest.raises(ValueError, h)
     s = repr(excinfo)
     assert s == "<ExceptionInfo ValueError tblen=4>"
 
@@ -344,29 +364,28 @@ def test_excinfo_no_sourcecode():
     except ValueError:
         excinfo = _pytest._code.ExceptionInfo()
     s = str(excinfo.traceback[-1])
     assert s == "  File '<string>':1 in <module>\n  ???\n"
 
 
 def test_excinfo_no_python_sourcecode(tmpdir):
     # XXX: simplified locally testable version
-    tmpdir.join('test.txt').write("{{ h()}}:")
+    tmpdir.join("test.txt").write("{{ h()}}:")
 
-    jinja2 = pytest.importorskip('jinja2')
+    jinja2 = pytest.importorskip("jinja2")
     loader = jinja2.FileSystemLoader(str(tmpdir))
     env = jinja2.Environment(loader=loader)
-    template = env.get_template('test.txt')
-    excinfo = pytest.raises(ValueError,
-                            template.render, h=h)
+    template = env.get_template("test.txt")
+    excinfo = pytest.raises(ValueError, template.render, h=h)
     for item in excinfo.traceback:
         print(item)  # XXX: for some reason jinja.Template.render is printed in full
         item.source  # shouldnt fail
-        if item.path.basename == 'test.txt':
-            assert str(item.source) == '{{ h()}}:'
+        if item.path.basename == "test.txt":
+            assert str(item.source) == "{{ h()}}:"
 
 
 def test_entrysource_Queue_example():
     try:
         queue.Queue().get(timeout=0.001)
     except queue.Empty:
         excinfo = _pytest._code.ExceptionInfo()
     entry = excinfo.traceback[-1]
@@ -386,136 +405,144 @@ def test_codepath_Queue_example():
     assert isinstance(path, py.path.local)
     assert path.basename.lower() == "queue.py"
     assert path.check()
 
 
 def test_match_succeeds():
     with pytest.raises(ZeroDivisionError) as excinfo:
         0 // 0
-    excinfo.match(r'.*zero.*')
+    excinfo.match(r".*zero.*")
 
 
 def test_match_raises_error(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         def test_division_zero():
             with pytest.raises(ZeroDivisionError) as excinfo:
                 0 / 0
             excinfo.match(r'[123]+')
-    """)
+    """
+    )
     result = testdir.runpytest()
     assert result.ret != 0
-    result.stdout.fnmatch_lines([
-        "*AssertionError*Pattern*[123]*not found*",
-    ])
+    result.stdout.fnmatch_lines(["*AssertionError*Pattern*[123]*not found*"])
 
 
 class TestFormattedExcinfo(object):
 
     @pytest.fixture
     def importasmod(self, request):
+
         def importasmod(source):
             source = _pytest._code.Source(source)
             tmpdir = request.getfixturevalue("tmpdir")
             modpath = tmpdir.join("mod.py")
             tmpdir.ensure("__init__.py")
             modpath.write(source)
             if invalidate_import_caches is not None:
                 invalidate_import_caches()
             return modpath.pyimport()
+
         return importasmod
 
     def excinfo_from_exec(self, source):
         source = _pytest._code.Source(source).strip()
         try:
             exec(source.compile())
         except KeyboardInterrupt:
             raise
         except:  # noqa
             return _pytest._code.ExceptionInfo()
         assert 0, "did not raise"
 
     def test_repr_source(self):
         pr = FormattedExcinfo()
-        source = _pytest._code.Source("""
+        source = _pytest._code.Source(
+            """
             def f(x):
                 pass
-        """).strip()
+        """
+        ).strip()
         pr.flow_marker = "|"
         lines = pr.get_source(source, 0)
         assert len(lines) == 2
         assert lines[0] == "|   def f(x):"
         assert lines[1] == "        pass"
 
     def test_repr_source_excinfo(self):
         """ check if indentation is right """
         pr = FormattedExcinfo()
-        excinfo = self.excinfo_from_exec("""
+        excinfo = self.excinfo_from_exec(
+            """
                 def f():
                     assert 0
                 f()
-        """)
+        """
+        )
         pr = FormattedExcinfo()
         source = pr._getentrysource(excinfo.traceback[-1])
         lines = pr.get_source(source, 1, excinfo)
-        assert lines == [
-            '    def f():',
-            '>       assert 0',
-            'E       AssertionError'
-        ]
+        assert lines == ["    def f():", ">       assert 0", "E       AssertionError"]
 
     def test_repr_source_not_existing(self):
         pr = FormattedExcinfo()
         co = compile("raise ValueError()", "", "exec")
         try:
             exec(co)
         except ValueError:
             excinfo = _pytest._code.ExceptionInfo()
         repr = pr.repr_excinfo(excinfo)
         assert repr.reprtraceback.reprentries[1].lines[0] == ">   ???"
-        if py.std.sys.version_info[0] >= 3:
+        if sys.version_info[0] >= 3:
             assert repr.chain[0][0].reprentries[1].lines[0] == ">   ???"
 
     def test_repr_many_line_source_not_existing(self):
         pr = FormattedExcinfo()
-        co = compile("""
+        co = compile(
+            """
 a = 1
 raise ValueError()
-""", "", "exec")
+""",
+            "",
+            "exec",
+        )
         try:
             exec(co)
         except ValueError:
             excinfo = _pytest._code.ExceptionInfo()
         repr = pr.repr_excinfo(excinfo)
         assert repr.reprtraceback.reprentries[1].lines[0] == ">   ???"
-        if py.std.sys.version_info[0] >= 3:
+        if sys.version_info[0] >= 3:
             assert repr.chain[0][0].reprentries[1].lines[0] == ">   ???"
 
     def test_repr_source_failing_fullsource(self):
         pr = FormattedExcinfo()
 
         class FakeCode(object):
+
             class raw(object):
-                co_filename = '?'
+                co_filename = "?"
 
-            path = '?'
+            path = "?"
             firstlineno = 5
 
             def fullsource(self):
                 return None
 
             fullsource = property(fullsource)
 
         class FakeFrame(object):
             code = FakeCode()
             f_locals = {}
             f_globals = {}
 
         class FakeTracebackEntry(_pytest._code.Traceback.Entry):
+
             def __init__(self, tb, excinfo=None):
                 self.lineno = 5 + 3
 
             @property
             def frame(self):
                 return FakeFrame()
 
         class Traceback(_pytest._code.Traceback):
@@ -537,315 +564,345 @@ raise ValueError()
         excinfo = FakeExcinfo()
 
         class FakeRawTB(object):
             tb_next = None
 
         tb = FakeRawTB()
         excinfo.traceback = Traceback(tb)
 
-        fail = IOError()  # noqa
+        fail = IOError()
         repr = pr.repr_excinfo(excinfo)
         assert repr.reprtraceback.reprentries[0].lines[0] == ">   ???"
-        if py.std.sys.version_info[0] >= 3:
+        if sys.version_info[0] >= 3:
             assert repr.chain[0][0].reprentries[0].lines[0] == ">   ???"
 
         fail = py.error.ENOENT  # noqa
         repr = pr.repr_excinfo(excinfo)
         assert repr.reprtraceback.reprentries[0].lines[0] == ">   ???"
-        if py.std.sys.version_info[0] >= 3:
+        if sys.version_info[0] >= 3:
             assert repr.chain[0][0].reprentries[0].lines[0] == ">   ???"
 
     def test_repr_local(self):
         p = FormattedExcinfo(showlocals=True)
-        loc = {'y': 5, 'z': 7, 'x': 3, '@x': 2, '__builtins__': {}}
+        loc = {"y": 5, "z": 7, "x": 3, "@x": 2, "__builtins__": {}}
         reprlocals = p.repr_locals(loc)
         assert reprlocals.lines
-        assert reprlocals.lines[0] == '__builtins__ = <builtins>'
-        assert reprlocals.lines[1] == 'x          = 3'
-        assert reprlocals.lines[2] == 'y          = 5'
-        assert reprlocals.lines[3] == 'z          = 7'
+        assert reprlocals.lines[0] == "__builtins__ = <builtins>"
+        assert reprlocals.lines[1] == "x          = 3"
+        assert reprlocals.lines[2] == "y          = 5"
+        assert reprlocals.lines[3] == "z          = 7"
 
     def test_repr_tracebackentry_lines(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def func1():
                 raise ValueError("hello\\nworld")
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.func1)
         excinfo.traceback = excinfo.traceback.filter()
         p = FormattedExcinfo()
         reprtb = p.repr_traceback_entry(excinfo.traceback[-1])
 
         # test as intermittent entry
         lines = reprtb.lines
-        assert lines[0] == '    def func1():'
+        assert lines[0] == "    def func1():"
         assert lines[1] == '>       raise ValueError("hello\\nworld")'
 
         # test as last entry
         p = FormattedExcinfo(showlocals=True)
         repr_entry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)
         lines = repr_entry.lines
-        assert lines[0] == '    def func1():'
+        assert lines[0] == "    def func1():"
         assert lines[1] == '>       raise ValueError("hello\\nworld")'
-        assert lines[2] == 'E       ValueError: hello'
-        assert lines[3] == 'E       world'
+        assert lines[2] == "E       ValueError: hello"
+        assert lines[3] == "E       world"
         assert not lines[4:]
 
         loc = repr_entry.reprlocals is not None
         loc = repr_entry.reprfileloc
         assert loc.path == mod.__file__
         assert loc.lineno == 3
         # assert loc.message == "ValueError: hello"
 
     def test_repr_tracebackentry_lines2(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def func1(m, x, y, z):
                 raise ValueError("hello\\nworld")
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.func1, "m" * 90, 5, 13, "z" * 120)
         excinfo.traceback = excinfo.traceback.filter()
         entry = excinfo.traceback[-1]
         p = FormattedExcinfo(funcargs=True)
         reprfuncargs = p.repr_args(entry)
-        assert reprfuncargs.args[0] == ('m', repr("m" * 90))
-        assert reprfuncargs.args[1] == ('x', '5')
-        assert reprfuncargs.args[2] == ('y', '13')
-        assert reprfuncargs.args[3] == ('z', repr("z" * 120))
+        assert reprfuncargs.args[0] == ("m", repr("m" * 90))
+        assert reprfuncargs.args[1] == ("x", "5")
+        assert reprfuncargs.args[2] == ("y", "13")
+        assert reprfuncargs.args[3] == ("z", repr("z" * 120))
 
         p = FormattedExcinfo(funcargs=True)
         repr_entry = p.repr_traceback_entry(entry)
         assert repr_entry.reprfuncargs.args == reprfuncargs.args
         tw = TWMock()
         repr_entry.toterminal(tw)
-        assert tw.lines[0] == "m = " + repr('m' * 90)
+        assert tw.lines[0] == "m = " + repr("m" * 90)
         assert tw.lines[1] == "x = 5, y = 13"
-        assert tw.lines[2] == "z = " + repr('z' * 120)
+        assert tw.lines[2] == "z = " + repr("z" * 120)
 
     def test_repr_tracebackentry_lines_var_kw_args(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def func1(x, *y, **z):
                 raise ValueError("hello\\nworld")
-        """)
-        excinfo = pytest.raises(ValueError, mod.func1, 'a', 'b', c='d')
+        """
+        )
+        excinfo = pytest.raises(ValueError, mod.func1, "a", "b", c="d")
         excinfo.traceback = excinfo.traceback.filter()
         entry = excinfo.traceback[-1]
         p = FormattedExcinfo(funcargs=True)
         reprfuncargs = p.repr_args(entry)
-        assert reprfuncargs.args[0] == ('x', repr('a'))
-        assert reprfuncargs.args[1] == ('y', repr(('b',)))
-        assert reprfuncargs.args[2] == ('z', repr({'c': 'd'}))
+        assert reprfuncargs.args[0] == ("x", repr("a"))
+        assert reprfuncargs.args[1] == ("y", repr(("b",)))
+        assert reprfuncargs.args[2] == ("z", repr({"c": "d"}))
 
         p = FormattedExcinfo(funcargs=True)
         repr_entry = p.repr_traceback_entry(entry)
         assert repr_entry.reprfuncargs.args == reprfuncargs.args
         tw = TWMock()
         repr_entry.toterminal(tw)
         assert tw.lines[0] == "x = 'a', y = ('b',), z = {'c': 'd'}"
 
     def test_repr_tracebackentry_short(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def func1():
                 raise ValueError("hello")
             def entry():
                 func1()
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.entry)
         p = FormattedExcinfo(style="short")
         reprtb = p.repr_traceback_entry(excinfo.traceback[-2])
         lines = reprtb.lines
         basename = py.path.local(mod.__file__).basename
-        assert lines[0] == '    func1()'
+        assert lines[0] == "    func1()"
         assert basename in str(reprtb.reprfileloc.path)
         assert reprtb.reprfileloc.lineno == 5
 
         # test last entry
         p = FormattedExcinfo(style="short")
         reprtb = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)
         lines = reprtb.lines
         assert lines[0] == '    raise ValueError("hello")'
-        assert lines[1] == 'E   ValueError: hello'
+        assert lines[1] == "E   ValueError: hello"
         assert basename in str(reprtb.reprfileloc.path)
         assert reprtb.reprfileloc.lineno == 3
 
     def test_repr_tracebackentry_no(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def func1():
                 raise ValueError("hello")
             def entry():
                 func1()
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.entry)
         p = FormattedExcinfo(style="no")
         p.repr_traceback_entry(excinfo.traceback[-2])
 
         p = FormattedExcinfo(style="no")
         reprentry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)
         lines = reprentry.lines
-        assert lines[0] == 'E   ValueError: hello'
+        assert lines[0] == "E   ValueError: hello"
         assert not lines[1:]
 
     def test_repr_traceback_tbfilter(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def f(x):
                 raise ValueError(x)
             def entry():
                 f(0)
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.entry)
         p = FormattedExcinfo(tbfilter=True)
         reprtb = p.repr_traceback(excinfo)
         assert len(reprtb.reprentries) == 2
         p = FormattedExcinfo(tbfilter=False)
         reprtb = p.repr_traceback(excinfo)
         assert len(reprtb.reprentries) == 3
 
     def test_traceback_short_no_source(self, importasmod, monkeypatch):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def func1():
                 raise ValueError("hello")
             def entry():
                 func1()
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.entry)
         from _pytest._code.code import Code
-        monkeypatch.setattr(Code, 'path', 'bogus')
+
+        monkeypatch.setattr(Code, "path", "bogus")
         excinfo.traceback[0].frame.code.path = "bogus"
         p = FormattedExcinfo(style="short")
         reprtb = p.repr_traceback_entry(excinfo.traceback[-2])
         lines = reprtb.lines
         last_p = FormattedExcinfo(style="short")
         last_reprtb = last_p.repr_traceback_entry(excinfo.traceback[-1], excinfo)
         last_lines = last_reprtb.lines
         monkeypatch.undo()
-        assert lines[0] == '    func1()'
+        assert lines[0] == "    func1()"
 
         assert last_lines[0] == '    raise ValueError("hello")'
-        assert last_lines[1] == 'E   ValueError: hello'
+        assert last_lines[1] == "E   ValueError: hello"
 
     def test_repr_traceback_and_excinfo(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def f(x):
                 raise ValueError(x)
             def entry():
                 f(0)
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.entry)
 
         for style in ("long", "short"):
             p = FormattedExcinfo(style=style)
             reprtb = p.repr_traceback(excinfo)
             assert len(reprtb.reprentries) == 2
             assert reprtb.style == style
             assert not reprtb.extraline
             repr = p.repr_excinfo(excinfo)
             assert repr.reprtraceback
             assert len(repr.reprtraceback.reprentries) == len(reprtb.reprentries)
-            if py.std.sys.version_info[0] >= 3:
+            if sys.version_info[0] >= 3:
                 assert repr.chain[0][0]
                 assert len(repr.chain[0][0].reprentries) == len(reprtb.reprentries)
             assert repr.reprcrash.path.endswith("mod.py")
             assert repr.reprcrash.message == "ValueError: 0"
 
     def test_repr_traceback_with_invalid_cwd(self, importasmod, monkeypatch):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def f(x):
                 raise ValueError(x)
             def entry():
                 f(0)
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.entry)
 
         p = FormattedExcinfo()
 
         def raiseos():
             raise OSError(2)
 
-        monkeypatch.setattr(py.std.os, 'getcwd', raiseos)
+        monkeypatch.setattr(os, "getcwd", raiseos)
         assert p._makepath(__file__) == __file__
         p.repr_traceback(excinfo)
 
     def test_repr_excinfo_addouterr(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def entry():
                 raise ValueError()
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.entry)
         repr = excinfo.getrepr()
         repr.addsection("title", "content")
         twmock = TWMock()
         repr.toterminal(twmock)
         assert twmock.lines[-1] == "content"
         assert twmock.lines[-2] == ("-", "title")
 
     def test_repr_excinfo_reprcrash(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def entry():
                 raise ValueError()
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.entry)
         repr = excinfo.getrepr()
         assert repr.reprcrash.path.endswith("mod.py")
         assert repr.reprcrash.lineno == 3
         assert repr.reprcrash.message == "ValueError"
         assert str(repr.reprcrash).endswith("mod.py:3: ValueError")
 
     def test_repr_traceback_recursion(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def rec2(x):
                 return rec1(x+1)
             def rec1(x):
                 return rec2(x-1)
             def entry():
                 rec1(42)
-        """)
+        """
+        )
         excinfo = pytest.raises(RuntimeError, mod.entry)
 
         for style in ("short", "long", "no"):
             p = FormattedExcinfo(style="short")
             reprtb = p.repr_traceback(excinfo)
             assert reprtb.extraline == "!!! Recursion detected (same locals & position)"
             assert str(reprtb)
 
     def test_reprexcinfo_getrepr(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def f(x):
                 raise ValueError(x)
             def entry():
                 f(0)
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.entry)
 
         for style in ("short", "long", "no"):
             for showlocals in (True, False):
                 repr = excinfo.getrepr(style=style, showlocals=showlocals)
-                if py.std.sys.version_info[0] < 3:
+                if sys.version_info[0] < 3:
                     assert isinstance(repr, ReprExceptionInfo)
                 assert repr.reprtraceback.style == style
-                if py.std.sys.version_info[0] >= 3:
+                if sys.version_info[0] >= 3:
                     assert isinstance(repr, ExceptionChainRepr)
                     for repr in repr.chain:
                         assert repr[0].style == style
 
     def test_reprexcinfo_unicode(self):
         from _pytest._code.code import TerminalRepr
 
         class MyRepr(TerminalRepr):
+
             def toterminal(self, tw):
                 tw.line(py.builtin._totext("я", "utf-8"))
 
         x = py.builtin._totext(MyRepr())
         assert x == py.builtin._totext("я", "utf-8")
 
     def test_toterminal_long(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def g(x):
                 raise ValueError(x)
             def f():
                 g(3)
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.f)
         excinfo.traceback = excinfo.traceback.filter()
         repr = excinfo.getrepr()
         tw = TWMock()
         repr.toterminal(tw)
         assert tw.lines[0] == ""
         tw.lines.pop(0)
         assert tw.lines[0] == "    def f():"
@@ -860,24 +917,26 @@ raise ValueError()
         assert tw.lines[8] == ">       raise ValueError(x)"
         assert tw.lines[9] == "E       ValueError: 3"
         assert tw.lines[10] == ""
         line = tw.get_write_msg(11)
         assert line.endswith("mod.py")
         assert tw.lines[12] == ":3: ValueError"
 
     def test_toterminal_long_missing_source(self, importasmod, tmpdir):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def g(x):
                 raise ValueError(x)
             def f():
                 g(3)
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.f)
-        tmpdir.join('mod.py').remove()
+        tmpdir.join("mod.py").remove()
         excinfo.traceback = excinfo.traceback.filter()
         repr = excinfo.getrepr()
         tw = TWMock()
         repr.toterminal(tw)
         assert tw.lines[0] == ""
         tw.lines.pop(0)
         assert tw.lines[0] == ">   ???"
         assert tw.lines[1] == ""
@@ -889,24 +948,26 @@ raise ValueError()
         assert tw.lines[6] == ">   ???"
         assert tw.lines[7] == "E   ValueError: 3"
         assert tw.lines[8] == ""
         line = tw.get_write_msg(9)
         assert line.endswith("mod.py")
         assert tw.lines[10] == ":3: ValueError"
 
     def test_toterminal_long_incomplete_source(self, importasmod, tmpdir):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def g(x):
                 raise ValueError(x)
             def f():
                 g(3)
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.f)
-        tmpdir.join('mod.py').write('asdf')
+        tmpdir.join("mod.py").write("asdf")
         excinfo.traceback = excinfo.traceback.filter()
         repr = excinfo.getrepr()
         tw = TWMock()
         repr.toterminal(tw)
         assert tw.lines[0] == ""
         tw.lines.pop(0)
         assert tw.lines[0] == ">   ???"
         assert tw.lines[1] == ""
@@ -918,20 +979,22 @@ raise ValueError()
         assert tw.lines[6] == ">   ???"
         assert tw.lines[7] == "E   ValueError: 3"
         assert tw.lines[8] == ""
         line = tw.get_write_msg(9)
         assert line.endswith("mod.py")
         assert tw.lines[10] == ":3: ValueError"
 
     def test_toterminal_long_filenames(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def f():
                 raise ValueError()
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.f)
         tw = TWMock()
         path = py.path.local(mod.__file__)
         old = path.dirpath().chdir()
         try:
             repr = excinfo.getrepr(abspath=False)
             repr.toterminal(tw)
             x = py.path.local().bestrelpath(path)
@@ -944,47 +1007,59 @@ raise ValueError()
             repr.toterminal(tw)
             msg = tw.get_write_msg(-2)
             assert msg == path
             line = tw.lines[-1]
             assert line == ":3: ValueError"
         finally:
             old.chdir()
 
-    @pytest.mark.parametrize('reproptions', [
-        {'style': style, 'showlocals': showlocals,
-         'funcargs': funcargs, 'tbfilter': tbfilter
-         } for style in ("long", "short", "no")
-        for showlocals in (True, False)
-        for tbfilter in (True, False)
-        for funcargs in (True, False)])
+    @pytest.mark.parametrize(
+        "reproptions",
+        [
+            {
+                "style": style,
+                "showlocals": showlocals,
+                "funcargs": funcargs,
+                "tbfilter": tbfilter,
+            }
+            for style in ("long", "short", "no")
+            for showlocals in (True, False)
+            for tbfilter in (True, False)
+            for funcargs in (True, False)
+        ],
+    )
     def test_format_excinfo(self, importasmod, reproptions):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def g(x):
                 raise ValueError(x)
             def f():
                 g(3)
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.f)
         tw = py.io.TerminalWriter(stringio=True)
         repr = excinfo.getrepr(**reproptions)
         repr.toterminal(tw)
         assert tw.stringio.getvalue()
 
     def test_traceback_repr_style(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def f():
                 g()
             def g():
                 h()
             def h():
                 i()
             def i():
                 raise ValueError()
-        """)
+        """
+        )
         excinfo = pytest.raises(ValueError, mod.f)
         excinfo.traceback = excinfo.traceback.filter()
         excinfo.traceback[1].set_repr_style("short")
         excinfo.traceback[2].set_repr_style("short")
         r = excinfo.getrepr(style="long")
         tw = TWMock()
         r.toterminal(tw)
         for line in tw.lines:
@@ -1010,236 +1085,273 @@ raise ValueError()
         assert tw.lines[17] == "E       ValueError"
         assert tw.lines[18] == ""
         msg = tw.get_write_msg(19)
         msg.endswith("mod.py")
         assert tw.lines[20] == ":9: ValueError"
 
     @pytest.mark.skipif("sys.version_info[0] < 3")
     def test_exc_chain_repr(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             class Err(Exception):
                 pass
             def f():
                 try:
                     g()
                 except Exception as e:
                     raise Err() from e
                 finally:
                     h()
             def g():
                 raise ValueError()
 
             def h():
                 raise AttributeError()
-        """)
+        """
+        )
         excinfo = pytest.raises(AttributeError, mod.f)
         r = excinfo.getrepr(style="long")
         tw = TWMock()
         r.toterminal(tw)
         for line in tw.lines:
             print(line)
         assert tw.lines[0] == ""
         assert tw.lines[1] == "    def f():"
         assert tw.lines[2] == "        try:"
         assert tw.lines[3] == ">           g()"
         assert tw.lines[4] == ""
         line = tw.get_write_msg(5)
-        assert line.endswith('mod.py')
-        assert tw.lines[6] == ':6: '
+        assert line.endswith("mod.py")
+        assert tw.lines[6] == ":6: "
         assert tw.lines[7] == ("_ ", None)
         assert tw.lines[8] == ""
         assert tw.lines[9] == "    def g():"
         assert tw.lines[10] == ">       raise ValueError()"
         assert tw.lines[11] == "E       ValueError"
         assert tw.lines[12] == ""
         line = tw.get_write_msg(13)
-        assert line.endswith('mod.py')
-        assert tw.lines[14] == ':12: ValueError'
+        assert line.endswith("mod.py")
+        assert tw.lines[14] == ":12: ValueError"
         assert tw.lines[15] == ""
-        assert tw.lines[16] == "The above exception was the direct cause of the following exception:"
+        assert (
+            tw.lines[16]
+            == "The above exception was the direct cause of the following exception:"
+        )
         assert tw.lines[17] == ""
         assert tw.lines[18] == "    def f():"
         assert tw.lines[19] == "        try:"
         assert tw.lines[20] == "            g()"
         assert tw.lines[21] == "        except Exception as e:"
         assert tw.lines[22] == ">           raise Err() from e"
         assert tw.lines[23] == "E           test_exc_chain_repr0.mod.Err"
         assert tw.lines[24] == ""
         line = tw.get_write_msg(25)
-        assert line.endswith('mod.py')
+        assert line.endswith("mod.py")
         assert tw.lines[26] == ":8: Err"
         assert tw.lines[27] == ""
-        assert tw.lines[28] == "During handling of the above exception, another exception occurred:"
+        assert (
+            tw.lines[28]
+            == "During handling of the above exception, another exception occurred:"
+        )
         assert tw.lines[29] == ""
         assert tw.lines[30] == "    def f():"
         assert tw.lines[31] == "        try:"
         assert tw.lines[32] == "            g()"
         assert tw.lines[33] == "        except Exception as e:"
         assert tw.lines[34] == "            raise Err() from e"
         assert tw.lines[35] == "        finally:"
         assert tw.lines[36] == ">           h()"
         assert tw.lines[37] == ""
         line = tw.get_write_msg(38)
-        assert line.endswith('mod.py')
+        assert line.endswith("mod.py")
         assert tw.lines[39] == ":10: "
-        assert tw.lines[40] == ('_ ', None)
+        assert tw.lines[40] == ("_ ", None)
         assert tw.lines[41] == ""
         assert tw.lines[42] == "    def h():"
         assert tw.lines[43] == ">       raise AttributeError()"
         assert tw.lines[44] == "E       AttributeError"
         assert tw.lines[45] == ""
         line = tw.get_write_msg(46)
-        assert line.endswith('mod.py')
+        assert line.endswith("mod.py")
         assert tw.lines[47] == ":15: AttributeError"
 
     @pytest.mark.skipif("sys.version_info[0] < 3")
     def test_exc_repr_with_raise_from_none_chain_suppression(self, importasmod):
-        mod = importasmod("""
+        mod = importasmod(
+            """
             def f():
                 try:
                     g()
                 except Exception:
                     raise AttributeError() from None
             def g():
                 raise ValueError()
-        """)
+        """
+        )
         excinfo = pytest.raises(AttributeError, mod.f)
         r = excinfo.getrepr(style="long")
         tw = TWMock()
         r.toterminal(tw)
         for line in tw.lines:
             print(line)
         assert tw.lines[0] == ""
         assert tw.lines[1] == "    def f():"
         assert tw.lines[2] == "        try:"
         assert tw.lines[3] == "            g()"
         assert tw.lines[4] == "        except Exception:"
         assert tw.lines[5] == ">           raise AttributeError() from None"
         assert tw.lines[6] == "E           AttributeError"
         assert tw.lines[7] == ""
         line = tw.get_write_msg(8)
-        assert line.endswith('mod.py')
+        assert line.endswith("mod.py")
         assert tw.lines[9] == ":6: AttributeError"
         assert len(tw.lines) == 10
 
     @pytest.mark.skipif("sys.version_info[0] < 3")
-    @pytest.mark.parametrize('reason, description', [
-        ('cause', 'The above exception was the direct cause of the following exception:'),
-        ('context', 'During handling of the above exception, another exception occurred:'),
-    ])
+    @pytest.mark.parametrize(
+        "reason, description",
+        [
+            (
+                "cause",
+                "The above exception was the direct cause of the following exception:",
+            ),
+            (
+                "context",
+                "During handling of the above exception, another exception occurred:",
+            ),
+        ],
+    )
     def test_exc_chain_repr_without_traceback(self, importasmod, reason, description):
         """
         Handle representation of exception chains where one of the exceptions doesn't have a
         real traceback, such as those raised in a subprocess submitted by the multiprocessing
         module (#1984).
         """
         from _pytest.pytester import LineMatcher
-        exc_handling_code = ' from e' if reason == 'cause' else ''
-        mod = importasmod("""
+
+        exc_handling_code = " from e" if reason == "cause" else ""
+        mod = importasmod(
+            """
             def f():
                 try:
                     g()
                 except Exception as e:
                     raise RuntimeError('runtime problem'){exc_handling_code}
             def g():
                 raise ValueError('invalid value')
-        """.format(exc_handling_code=exc_handling_code))
+        """.format(
+                exc_handling_code=exc_handling_code
+            )
+        )
 
         with pytest.raises(RuntimeError) as excinfo:
             mod.f()
 
         # emulate the issue described in #1984
-        attr = '__%s__' % reason
+        attr = "__%s__" % reason
         getattr(excinfo.value, attr).__traceback__ = None
 
         r = excinfo.getrepr()
         tw = py.io.TerminalWriter(stringio=True)
         tw.hasmarkup = False
         r.toterminal(tw)
 
         matcher = LineMatcher(tw.stringio.getvalue().splitlines())
-        matcher.fnmatch_lines([
-            "ValueError: invalid value",
-            description,
-            "* except Exception as e:",
-            "> * raise RuntimeError('runtime problem')" + exc_handling_code,
-            "E *RuntimeError: runtime problem",
-        ])
+        matcher.fnmatch_lines(
+            [
+                "ValueError: invalid value",
+                description,
+                "* except Exception as e:",
+                "> * raise RuntimeError('runtime problem')" + exc_handling_code,
+                "E *RuntimeError: runtime problem",
+            ]
+        )
 
 
 @pytest.mark.parametrize("style", ["short", "long"])
 @pytest.mark.parametrize("encoding", [None, "utf8", "utf16"])
 def test_repr_traceback_with_unicode(style, encoding):
-    msg = u'☹'
+    msg = u"☹"
     if encoding is not None:
         msg = msg.encode(encoding)
     try:
         raise RuntimeError(msg)
     except RuntimeError:
         e_info = ExceptionInfo()
     formatter = FormattedExcinfo(style=style)
     repr_traceback = formatter.repr_traceback(e_info)
     assert repr_traceback is not None
 
 
 def test_cwd_deleted(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test(tmpdir):
             tmpdir.chdir()
             tmpdir.remove()
             assert False
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines(['* 1 failed in *'])
-    assert 'INTERNALERROR' not in result.stdout.str() + result.stderr.str()
+    result.stdout.fnmatch_lines(["* 1 failed in *"])
+    assert "INTERNALERROR" not in result.stdout.str() + result.stderr.str()
 
 
 def test_exception_repr_extraction_error_on_recursion():
     """
     Ensure we can properly detect a recursion error even
-    if some locals raise error on comparision (#2459).
+    if some locals raise error on comparison (#2459).
     """
+
     class numpy_like(object):
 
         def __eq__(self, other):
             if type(other) is numpy_like:
-                raise ValueError('The truth value of an array '
-                                 'with more than one element is ambiguous.')
+                raise ValueError(
+                    "The truth value of an array "
+                    "with more than one element is ambiguous."
+                )
 
     def a(x):
         return b(numpy_like())
 
     def b(x):
         return a(numpy_like())
 
     try:
         a(numpy_like())
     except:  # noqa
         from _pytest._code.code import ExceptionInfo
         from _pytest.pytester import LineMatcher
+
         exc_info = ExceptionInfo()
 
         matcher = LineMatcher(str(exc_info.getrepr()).splitlines())
-        matcher.fnmatch_lines([
-            '!!! Recursion error detected, but an error occurred locating the origin of recursion.',
-            '*The following exception happened*',
-            '*ValueError: The truth value of an array*',
-        ])
+        matcher.fnmatch_lines(
+            [
+                "!!! Recursion error detected, but an error occurred locating the origin of recursion.",
+                "*The following exception happened*",
+                "*ValueError: The truth value of an array*",
+            ]
+        )
 
 
 def test_no_recursion_index_on_recursion_error():
     """
     Ensure that we don't break in case we can't find the recursion index
     during a recursion error (#2486).
     """
     try:
+
         class RecursionDepthError(object):
+
             def __getattr__(self, attr):
-                return getattr(self, '_' + attr)
+                return getattr(self, "_" + attr)
 
         RecursionDepthError().trigger
     except:  # noqa
         from _pytest._code.code import ExceptionInfo
+
         exc_info = ExceptionInfo()
-        assert 'maximum recursion' in str(exc_info.getrepr())
+        assert "maximum recursion" in str(exc_info.getrepr())
     else:
         assert 0
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/code/test_source.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/code/test_source.py
@@ -1,150 +1,167 @@
 # flake8: noqa
 # disable flake check on this file because some constructs are strange
 # or redundant on purpose and can't be disable on a line-by-line basis
 from __future__ import absolute_import, division, print_function
+import inspect
 import sys
 
 import _pytest._code
 import py
 import pytest
 from _pytest._code import Source
-from _pytest._code.source import _ast
+from _pytest._code.source import ast
 
-if _ast is not None:
-    astonly = pytest.mark.nothing
-else:
-    astonly = pytest.mark.xfail("True", reason="only works with AST-compile")
 
+astonly = pytest.mark.nothing
 failsonjython = pytest.mark.xfail("sys.platform.startswith('java')")
 
 
 def test_source_str_function():
     x = Source("3")
     assert str(x) == "3"
 
     x = Source("   3")
     assert str(x) == "3"
 
-    x = Source("""
+    x = Source(
+        """
         3
-    """, rstrip=False)
+    """,
+        rstrip=False,
+    )
     assert str(x) == "\n3\n    "
 
-    x = Source("""
+    x = Source(
+        """
         3
-    """, rstrip=True)
+    """,
+        rstrip=True,
+    )
     assert str(x) == "\n3"
 
 
 def test_unicode():
     try:
         unicode
     except NameError:
         return
     x = Source(unicode("4"))
     assert str(x) == "4"
-    co = _pytest._code.compile(unicode('u"\xc3\xa5"', 'utf8'), mode='eval')
+    co = _pytest._code.compile(unicode('u"\xc3\xa5"', "utf8"), mode="eval")
     val = eval(co)
     assert isinstance(val, unicode)
 
 
 def test_source_from_function():
     source = _pytest._code.Source(test_source_str_function)
-    assert str(source).startswith('def test_source_str_function():')
+    assert str(source).startswith("def test_source_str_function():")
 
 
 def test_source_from_method():
+
     class TestClass(object):
+
         def test_method(self):
             pass
+
     source = _pytest._code.Source(TestClass().test_method)
-    assert source.lines == ["def test_method(self):",
-                            "    pass"]
+    assert source.lines == ["def test_method(self):", "    pass"]
 
 
 def test_source_from_lines():
     lines = ["a \n", "b\n", "c"]
     source = _pytest._code.Source(lines)
-    assert source.lines == ['a ', 'b', 'c']
+    assert source.lines == ["a ", "b", "c"]
 
 
 def test_source_from_inner_function():
+
     def f():
         pass
+
     source = _pytest._code.Source(f, deindent=False)
-    assert str(source).startswith('    def f():')
+    assert str(source).startswith("    def f():")
     source = _pytest._code.Source(f)
-    assert str(source).startswith('def f():')
+    assert str(source).startswith("def f():")
 
 
 def test_source_putaround_simple():
     source = Source("raise ValueError")
     source = source.putaround(
-        "try:", """\
+        "try:",
+        """\
         except ValueError:
             x = 42
         else:
-            x = 23""")
-    assert str(source) == """\
+            x = 23""",
+    )
+    assert (
+        str(source)
+        == """\
 try:
     raise ValueError
 except ValueError:
     x = 42
 else:
     x = 23"""
+    )
 
 
 def test_source_putaround():
     source = Source()
-    source = source.putaround("""
+    source = source.putaround(
+        """
         if 1:
             x=1
-    """)
+    """
+    )
     assert str(source).strip() == "if 1:\n    x=1"
 
 
 def test_source_strips():
     source = Source("")
     assert source == Source()
-    assert str(source) == ''
+    assert str(source) == ""
     assert source.strip() == source
 
 
 def test_source_strip_multiline():
     source = Source()
     source.lines = ["", " hello", "  "]
     source2 = source.strip()
     assert source2.lines == [" hello"]
 
 
 def test_syntaxerror_rerepresentation():
-    ex = pytest.raises(SyntaxError, _pytest._code.compile, 'xyz xyz')
+    ex = pytest.raises(SyntaxError, _pytest._code.compile, "xyz xyz")
     assert ex.value.lineno == 1
     assert ex.value.offset in (4, 7)  # XXX pypy/jython versus cpython?
-    assert ex.value.text.strip(), 'x x'
+    assert ex.value.text.strip(), "x x"
 
 
 def test_isparseable():
     assert Source("hello").isparseable()
     assert Source("if 1:\n  pass").isparseable()
     assert Source(" \nif 1:\n  pass").isparseable()
     assert not Source("if 1:\n").isparseable()
     assert not Source(" \nif 1:\npass").isparseable()
     assert not Source(chr(0)).isparseable()
 
 
 class TestAccesses(object):
-    source = Source("""\
+    source = Source(
+        """\
         def f(x):
             pass
         def g(x):
             pass
-    """)
+    """
+    )
 
     def test_getrange(self):
         x = self.source[0:2]
         assert x.isparseable()
         assert len(x.lines) == 2
         assert str(x) == "def f(x):\n    pass"
 
     def test_getline(self):
@@ -155,301 +172,344 @@ class TestAccesses(object):
         assert len(self.source) == 4
 
     def test_iter(self):
         values = [x for x in self.source]
         assert len(values) == 4
 
 
 class TestSourceParsingAndCompiling(object):
-    source = Source("""\
+    source = Source(
+        """\
         def f(x):
             assert (x ==
                     3 +
                     4)
-    """).strip()
+    """
+    ).strip()
 
     def test_compile(self):
         co = _pytest._code.compile("x=3")
         d = {}
         exec(co, d)
-        assert d['x'] == 3
+        assert d["x"] == 3
 
     def test_compile_and_getsource_simple(self):
         co = _pytest._code.compile("x=3")
         exec(co)
         source = _pytest._code.Source(co)
         assert str(source) == "x=3"
 
     def test_compile_and_getsource_through_same_function(self):
+
         def gensource(source):
             return _pytest._code.compile(source)
-        co1 = gensource("""
+
+        co1 = gensource(
+            """
             def f():
                 raise KeyError()
-        """)
-        co2 = gensource("""
+        """
+        )
+        co2 = gensource(
+            """
             def f():
                 raise ValueError()
-        """)
-        source1 = py.std.inspect.getsource(co1)
-        assert 'KeyError' in source1
-        source2 = py.std.inspect.getsource(co2)
-        assert 'ValueError' in source2
+        """
+        )
+        source1 = inspect.getsource(co1)
+        assert "KeyError" in source1
+        source2 = inspect.getsource(co2)
+        assert "ValueError" in source2
 
     def test_getstatement(self):
         # print str(self.source)
         ass = str(self.source[1:])
         for i in range(1, 4):
             # print "trying start in line %r" % self.source[i]
             s = self.source.getstatement(i)
-            #x = s.deindent()
+            # x = s.deindent()
             assert str(s) == ass
 
     def test_getstatementrange_triple_quoted(self):
         # print str(self.source)
-        source = Source("""hello('''
-        ''')""")
+        source = Source(
+            """hello('''
+        ''')"""
+        )
         s = source.getstatement(0)
         assert s == str(source)
         s = source.getstatement(1)
         assert s == str(source)
 
     @astonly
     def test_getstatementrange_within_constructs(self):
-        source = Source("""\
+        source = Source(
+            """\
             try:
                 try:
                     raise ValueError
                 except SomeThing:
                     pass
             finally:
                 42
-        """)
+        """
+        )
         assert len(source) == 7
         # check all lineno's that could occur in a traceback
         # assert source.getstatementrange(0) == (0, 7)
         # assert source.getstatementrange(1) == (1, 5)
         assert source.getstatementrange(2) == (2, 3)
         assert source.getstatementrange(3) == (3, 4)
         assert source.getstatementrange(4) == (4, 5)
         # assert source.getstatementrange(5) == (0, 7)
         assert source.getstatementrange(6) == (6, 7)
 
     def test_getstatementrange_bug(self):
-        source = Source("""\
+        source = Source(
+            """\
             try:
                 x = (
                    y +
                    z)
             except:
                 pass
-        """)
+        """
+        )
         assert len(source) == 6
         assert source.getstatementrange(2) == (1, 4)
 
     def test_getstatementrange_bug2(self):
-        source = Source("""\
+        source = Source(
+            """\
             assert (
                 33
                 ==
                 [
                   X(3,
                       b=1, c=2
                    ),
                 ]
               )
-        """)
+        """
+        )
         assert len(source) == 9
         assert source.getstatementrange(5) == (0, 9)
 
     def test_getstatementrange_ast_issue58(self):
-        source = Source("""\
+        source = Source(
+            """\
 
             def test_some():
                 for a in [a for a in
                     CAUSE_ERROR]: pass
 
             x = 3
-        """)
+        """
+        )
         assert getstatement(2, source).lines == source.lines[2:3]
         assert getstatement(3, source).lines == source.lines[3:4]
 
     def test_getstatementrange_out_of_bounds_py3(self):
         source = Source("if xxx:\n   from .collections import something")
         r = source.getstatementrange(1)
         assert r == (1, 2)
 
     def test_getstatementrange_with_syntaxerror_issue7(self):
         source = Source(":")
         pytest.raises(SyntaxError, lambda: source.getstatementrange(0))
 
     def test_compile_to_ast(self):
         import ast
+
         source = Source("x = 4")
         mod = source.compile(flag=ast.PyCF_ONLY_AST)
         assert isinstance(mod, ast.Module)
         compile(mod, "<filename>", "exec")
 
     def test_compile_and_getsource(self):
         co = self.source.compile()
         py.builtin.exec_(co, globals())
         f(7)
         excinfo = pytest.raises(AssertionError, "f(6)")
         frame = excinfo.traceback[-1].frame
         stmt = frame.code.fullsource.getstatement(frame.lineno)
         # print "block", str(block)
-        assert str(stmt).strip().startswith('assert')
+        assert str(stmt).strip().startswith("assert")
 
-    @pytest.mark.parametrize('name', ['', None, 'my'])
+    @pytest.mark.parametrize("name", ["", None, "my"])
     def test_compilefuncs_and_path_sanity(self, name):
+
         def check(comp, name):
             co = comp(self.source, name)
             if not name:
-                expected = "codegen %s:%d>" % (mypath, mylineno + 2 + 2)
+                expected = "codegen %s:%d>" % (mypath, mylineno + 2 + 3)
             else:
-                expected = "codegen %r %s:%d>" % (name, mypath, mylineno + 2 + 2)
+                expected = "codegen %r %s:%d>" % (name, mypath, mylineno + 2 + 3)
             fn = co.co_filename
             assert fn.endswith(expected)
 
         mycode = _pytest._code.Code(self.test_compilefuncs_and_path_sanity)
         mylineno = mycode.firstlineno
         mypath = mycode.path
 
         for comp in _pytest._code.compile, _pytest._code.Source.compile:
             check(comp, name)
 
     def test_offsetless_synerr(self):
-        pytest.raises(SyntaxError, _pytest._code.compile, "lambda a,a: 0", mode='eval')
+        pytest.raises(SyntaxError, _pytest._code.compile, "lambda a,a: 0", mode="eval")
 
 
 def test_getstartingblock_singleline():
+
     class A(object):
+
         def __init__(self, *args):
             frame = sys._getframe(1)
             self.source = _pytest._code.Frame(frame).statement
 
-    x = A('x', 'y')
+    x = A("x", "y")
 
     values = [i for i in x.source.lines if i.strip()]
     assert len(values) == 1
 
 
 def test_getline_finally():
-    def c(): pass
-    excinfo = pytest.raises(TypeError, """
+
+    def c():
+        pass
+
+    excinfo = pytest.raises(
+        TypeError,
+        """
            teardown = None
            try:
                 c(1)
            finally:
                 if teardown:
                     teardown()
-    """)
+    """,
+    )
     source = excinfo.traceback[-1].statement
-    assert str(source).strip() == 'c(1)'
+    assert str(source).strip() == "c(1)"
 
 
 def test_getfuncsource_dynamic():
     source = """
         def f():
             raise ValueError
 
         def g(): pass
     """
     co = _pytest._code.compile(source)
     py.builtin.exec_(co, globals())
-    assert str(_pytest._code.Source(f)).strip() == 'def f():\n    raise ValueError'
-    assert str(_pytest._code.Source(g)).strip() == 'def g(): pass'
+    assert str(_pytest._code.Source(f)).strip() == "def f():\n    raise ValueError"
+    assert str(_pytest._code.Source(g)).strip() == "def g(): pass"
 
 
 def test_getfuncsource_with_multine_string():
+
     def f():
-        c = '''while True:
+        c = """while True:
     pass
-'''
-    assert str(_pytest._code.Source(f)).strip() == "def f():\n    c = '''while True:\n    pass\n'''"
+"""
+
+    assert (
+        str(_pytest._code.Source(f)).strip()
+        == 'def f():\n    c = """while True:\n    pass\n"""'
+    )
 
 
 def test_deindent():
     from _pytest._code.source import deindent as deindent
-    assert deindent(['\tfoo', '\tbar', ]) == ['foo', 'bar']
+
+    assert deindent(["\tfoo", "\tbar"]) == ["foo", "bar"]
 
     def f():
-        c = '''while True:
+        c = """while True:
     pass
-'''
-    import inspect
+"""
+
     lines = deindent(inspect.getsource(f).splitlines())
-    assert lines == ["def f():", "    c = '''while True:", "    pass", "'''"]
+    assert lines == ["def f():", '    c = """while True:', "    pass", '"""']
 
     source = """
         def f():
             def g():
                 pass
     """
     lines = deindent(source.splitlines())
-    assert lines == ['', 'def f():', '    def g():', '        pass', '    ']
+    assert lines == ["", "def f():", "    def g():", "        pass", "    "]
 
 
 def test_source_of_class_at_eof_without_newline(tmpdir):
     # this test fails because the implicit inspect.getsource(A) below
     # does not return the "x = 1" last line.
-    source = _pytest._code.Source('''
+    source = _pytest._code.Source(
+        """
         class A(object):
             def method(self):
                 x = 1
-    ''')
+    """
+    )
     path = tmpdir.join("a.py")
     path.write(source)
     s2 = _pytest._code.Source(tmpdir.join("a.py").pyimport().A)
     assert str(source).strip() == str(s2).strip()
 
 
 if True:
+
     def x():
         pass
 
 
 def test_getsource_fallback():
     from _pytest._code.source import getsource
+
     expected = """def x():
     pass"""
     src = getsource(x)
     assert src == expected
 
 
 def test_idem_compile_and_getsource():
     from _pytest._code.source import getsource
+
     expected = "def x(): pass"
     co = _pytest._code.compile(expected)
     src = getsource(co)
     assert src == expected
 
 
 def test_findsource_fallback():
     from _pytest._code.source import findsource
+
     src, lineno = findsource(x)
-    assert 'test_findsource_simple' in str(src)
-    assert src[lineno] == '    def x():'
+    assert "test_findsource_simple" in str(src)
+    assert src[lineno] == "    def x():"
 
 
 def test_findsource():
     from _pytest._code.source import findsource
-    co = _pytest._code.compile("""if 1:
+
+    co = _pytest._code.compile(
+        """if 1:
     def x():
         pass
-""")
+"""
+    )
 
     src, lineno = findsource(co)
-    assert 'if 1:' in str(src)
+    assert "if 1:" in str(src)
 
     d = {}
     eval(co, d)
-    src, lineno = findsource(d['x'])
-    assert 'if 1:' in str(src)
+    src, lineno = findsource(d["x"])
+    assert "if 1:" in str(src)
     assert src[lineno] == "    def x():"
 
 
 def test_getfslineno():
     from _pytest._code import getfslineno
 
     def f(x):
         pass
@@ -459,128 +519,146 @@ def test_getfslineno():
     assert fspath.basename == "test_source.py"
     assert lineno == _pytest._code.getrawcode(f).co_firstlineno - 1  # see findsource
 
     class A(object):
         pass
 
     fspath, lineno = getfslineno(A)
 
-    _, A_lineno = py.std.inspect.findsource(A)
+    _, A_lineno = inspect.findsource(A)
     assert fspath.basename == "test_source.py"
     assert lineno == A_lineno
 
     assert getfslineno(3) == ("", -1)
 
     class B(object):
         pass
+
     B.__name__ = "B2"
     assert getfslineno(B)[1] == -1
 
 
 def test_code_of_object_instance_with_call():
+
     class A(object):
         pass
+
     pytest.raises(TypeError, lambda: _pytest._code.Source(A()))
 
     class WithCall(object):
+
         def __call__(self):
             pass
 
     code = _pytest._code.Code(WithCall())
-    assert 'pass' in str(code.source())
+    assert "pass" in str(code.source())
 
     class Hello(object):
+
         def __call__(self):
             pass
+
     pytest.raises(TypeError, lambda: _pytest._code.Code(Hello))
 
 
 def getstatement(lineno, source):
     from _pytest._code.source import getstatementrange_ast
+
     source = _pytest._code.Source(source, deindent=False)
     ast, start, end = getstatementrange_ast(lineno, source)
     return source[start:end]
 
 
 def test_oneline():
     source = getstatement(0, "raise ValueError")
     assert str(source) == "raise ValueError"
 
 
 def test_comment_and_no_newline_at_end():
     from _pytest._code.source import getstatementrange_ast
-    source = Source(['def test_basic_complex():',
-                     '    assert 1 == 2',
-                     '# vim: filetype=pyopencl:fdm=marker'])
+
+    source = Source(
+        [
+            "def test_basic_complex():",
+            "    assert 1 == 2",
+            "# vim: filetype=pyopencl:fdm=marker",
+        ]
+    )
     ast, start, end = getstatementrange_ast(1, source)
     assert end == 2
 
 
 def test_oneline_and_comment():
     source = getstatement(0, "raise ValueError\n#hello")
     assert str(source) == "raise ValueError"
 
 
-@pytest.mark.xfail(hasattr(sys, "pypy_version_info"),
-                   reason='does not work on pypy')
+@pytest.mark.xfail(hasattr(sys, "pypy_version_info"), reason="does not work on pypy")
 def test_comments():
     source = '''def test():
     "comment 1"
     x = 1
       # comment 2
     # comment 3
 
     assert False
 
 """
 comment 4
 """
 '''
     for line in range(2, 6):
-        assert str(getstatement(line, source)) == '    x = 1'
+        assert str(getstatement(line, source)) == "    x = 1"
     for line in range(6, 10):
-        assert str(getstatement(line, source)) == '    assert False'
+        assert str(getstatement(line, source)) == "    assert False"
     assert str(getstatement(10, source)) == '"""'
 
 
 def test_comment_in_statement():
-    source = '''test(foo=1,
+    source = """test(foo=1,
     # comment 1
     bar=2)
-'''
+"""
     for line in range(1, 3):
-        assert str(getstatement(line, source)) == \
-            'test(foo=1,\n    # comment 1\n    bar=2)'
+        assert (
+            str(getstatement(line, source))
+            == "test(foo=1,\n    # comment 1\n    bar=2)"
+        )
 
 
 def test_single_line_else():
     source = getstatement(1, "if False: 2\nelse: 3")
     assert str(source) == "else: 3"
 
 
 def test_single_line_finally():
     source = getstatement(1, "try: 1\nfinally: 3")
     assert str(source) == "finally: 3"
 
 
 def test_issue55():
-    source = ('def round_trip(dinp):\n  assert 1 == dinp\n'
-              'def test_rt():\n  round_trip("""\n""")\n')
+    source = (
+        "def round_trip(dinp):\n  assert 1 == dinp\n"
+        'def test_rt():\n  round_trip("""\n""")\n'
+    )
     s = getstatement(3, source)
     assert str(s) == '  round_trip("""\n""")'
 
 
 def XXXtest_multiline():
-    source = getstatement(0, """\
+    source = getstatement(
+        0,
+        """\
 raise ValueError(
     23
 )
 x = 3
-""")
+""",
+    )
     assert str(source) == "raise ValueError(\n    23\n)"
 
 
 class TestTry(object):
     pytestmark = astonly
     source = """\
 try:
     raise ValueError
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/code/test_source_multiline_block.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/code/test_source_multiline_block.py
@@ -7,20 +7,23 @@ import _pytest._code
 def test_getstartingblock_multiline():
     """
     This test was originally found in test_source.py, but it depends on the weird
     formatting of the ``x = A`` construct seen here and our autopep8 tool can only exclude entire
     files (it does not support excluding lines/blocks using the traditional #noqa comment yet,
     see hhatto/autopep8#307). It was considered better to just move this single test to its own
     file and exclude it from autopep8 than try to complicate things.
     """
+
     class A(object):
+
         def __init__(self, *args):
             frame = sys._getframe(1)
             self.source = _pytest._code.Frame(frame).statement
 
+    # fmt: off
     x = A('x',
           'y'
           ,
           'z')
-
+    # fmt: on
     values = [i for i in x.source.lines if i.strip()]
     assert len(values) == 4
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/deprecated_test.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/deprecated_test.py
@@ -1,127 +1,265 @@
 from __future__ import absolute_import, division, print_function
 import pytest
 
 
 def test_yield_tests_deprecation(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def func1(arg, arg2):
             assert arg == arg2
         def test_gen():
             yield "m1", func1, 15, 3*5
             yield "m2", func1, 42, 6*7
         def test_gen2():
             for k in range(10):
                 yield func1, 1, 1
-    """)
-    result = testdir.runpytest('-ra')
-    result.stdout.fnmatch_lines([
-        '*yield tests are deprecated, and scheduled to be removed in pytest 4.0*',
-        '*2 passed*',
-    ])
-    assert result.stdout.str().count('yield tests are deprecated') == 2
+    """
+    )
+    result = testdir.runpytest("-ra")
+    result.stdout.fnmatch_lines(
+        [
+            "*yield tests are deprecated, and scheduled to be removed in pytest 4.0*",
+            "*2 passed*",
+        ]
+    )
+    assert result.stdout.str().count("yield tests are deprecated") == 2
 
 
 def test_funcarg_prefix_deprecation(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def pytest_funcarg__value():
             return 10
 
         def test_funcarg_prefix(value):
             assert value == 10
-    """)
-    result = testdir.runpytest('-ra')
-    result.stdout.fnmatch_lines([
-        ('*pytest_funcarg__value: '
-         '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.'),
-        '*1 passed*',
-    ])
+    """
+    )
+    result = testdir.runpytest("-ra")
+    result.stdout.fnmatch_lines(
+        [
+            (
+                "*pytest_funcarg__value: "
+                '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."
+            ),
+            "*1 passed*",
+        ]
+    )
 
 
 def test_pytest_setup_cfg_deprecated(testdir):
-    testdir.makefile('.cfg', setup='''
+    testdir.makefile(
+        ".cfg",
+        setup="""
         [pytest]
         addopts = --verbose
-    ''')
+    """,
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines(['*pytest*section in setup.cfg files is deprecated*use*tool:pytest*instead*'])
+    result.stdout.fnmatch_lines(
+        ["*pytest*section in setup.cfg files is deprecated*use*tool:pytest*instead*"]
+    )
+
+
+def test_pytest_custom_cfg_deprecated(testdir):
+    testdir.makefile(
+        ".cfg",
+        custom="""
+        [pytest]
+        addopts = --verbose
+    """,
+    )
+    result = testdir.runpytest("-c", "custom.cfg")
+    result.stdout.fnmatch_lines(
+        ["*pytest*section in custom.cfg files is deprecated*use*tool:pytest*instead*"]
+    )
 
 
 def test_str_args_deprecated(tmpdir, testdir):
     """Deprecate passing strings to pytest.main(). Scheduled for removal in pytest-4.0."""
     from _pytest.main import EXIT_NOTESTSCOLLECTED
+
     warnings = []
 
     class Collect(object):
+
         def pytest_logwarning(self, message):
             warnings.append(message)
 
     ret = pytest.main("%s -x" % tmpdir, plugins=[Collect()])
-    testdir.delete_loaded_modules()
-    msg = ('passing a string to pytest.main() is deprecated, '
-           'pass a list of arguments instead.')
+    msg = (
+        "passing a string to pytest.main() is deprecated, "
+        "pass a list of arguments instead."
+    )
     assert msg in warnings
     assert ret == EXIT_NOTESTSCOLLECTED
 
 
 def test_getfuncargvalue_is_deprecated(request):
-    pytest.deprecated_call(request.getfuncargvalue, 'tmpdir')
+    pytest.deprecated_call(request.getfuncargvalue, "tmpdir")
 
 
 def test_resultlog_is_deprecated(testdir):
-    result = testdir.runpytest('--help')
-    result.stdout.fnmatch_lines(['*DEPRECATED path for machine-readable result log*'])
+    result = testdir.runpytest("--help")
+    result.stdout.fnmatch_lines(["*DEPRECATED path for machine-readable result log*"])
 
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         def test():
             pass
-    ''')
-    result = testdir.runpytest('--result-log=%s' % testdir.tmpdir.join('result.log'))
-    result.stdout.fnmatch_lines([
-        '*--result-log is deprecated and scheduled for removal in pytest 4.0*',
-        '*See https://docs.pytest.org/*/usage.html#creating-resultlog-format-files for more information*',
-    ])
+    """
+    )
+    result = testdir.runpytest("--result-log=%s" % testdir.tmpdir.join("result.log"))
+    result.stdout.fnmatch_lines(
+        [
+            "*--result-log is deprecated and scheduled for removal in pytest 4.0*",
+            "*See https://docs.pytest.org/*/usage.html#creating-resultlog-format-files for more information*",
+        ]
+    )
 
 
-@pytest.mark.filterwarnings('always:Metafunc.addcall is deprecated')
+@pytest.mark.filterwarnings("always:Metafunc.addcall is deprecated")
 def test_metafunc_addcall_deprecated(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def pytest_generate_tests(metafunc):
             metafunc.addcall({'i': 1})
             metafunc.addcall({'i': 2})
         def test_func(i):
             pass
-    """)
-    res = testdir.runpytest('-s')
+    """
+    )
+    res = testdir.runpytest("-s")
     assert res.ret == 0
-    res.stdout.fnmatch_lines([
-        "*Metafunc.addcall is deprecated*",
-        "*2 passed, 2 warnings*",
-    ])
+    res.stdout.fnmatch_lines(
+        ["*Metafunc.addcall is deprecated*", "*2 passed, 2 warnings*"]
+    )
 
 
 def test_terminal_reporter_writer_attr(pytestconfig):
     """Check that TerminalReporter._tw is also available as 'writer' (#2984)
     This attribute is planned to be deprecated in 3.4.
     """
     try:
         import xdist  # noqa
-        pytest.skip('xdist workers disable the terminal reporter plugin')
+
+        pytest.skip("xdist workers disable the terminal reporter plugin")
     except ImportError:
         pass
-    terminal_reporter = pytestconfig.pluginmanager.get_plugin('terminalreporter')
+    terminal_reporter = pytestconfig.pluginmanager.get_plugin("terminalreporter")
     assert terminal_reporter.writer is terminal_reporter._tw
 
 
-def test_pytest_catchlog_deprecated(testdir):
-    testdir.makepyfile("""
+@pytest.mark.parametrize("plugin", ["catchlog", "capturelog"])
+def test_pytest_catchlog_deprecated(testdir, plugin):
+    testdir.makepyfile(
+        """
         def test_func(pytestconfig):
-            pytestconfig.pluginmanager.register(None, 'pytest_catchlog')
-    """)
+            pytestconfig.pluginmanager.register(None, 'pytest_{}')
+    """.format(
+            plugin
+        )
+    )
     res = testdir.runpytest()
     assert res.ret == 0
-    res.stdout.fnmatch_lines([
-        "*pytest-catchlog plugin has been merged into the core*",
-        "*1 passed, 1 warnings*",
-    ])
+    res.stdout.fnmatch_lines(
+        ["*pytest-*log plugin has been merged into the core*", "*1 passed, 1 warnings*"]
+    )
+
+
+def test_pytest_plugins_in_non_top_level_conftest_deprecated(testdir):
+    from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST
+
+    subdirectory = testdir.tmpdir.join("subdirectory")
+    subdirectory.mkdir()
+    # create the inner conftest with makeconftest and then move it to the subdirectory
+    testdir.makeconftest(
+        """
+        pytest_plugins=['capture']
+    """
+    )
+    testdir.tmpdir.join("conftest.py").move(subdirectory.join("conftest.py"))
+    # make the top level conftest
+    testdir.makeconftest(
+        """
+        import warnings
+        warnings.filterwarnings('always', category=DeprecationWarning)
+    """
+    )
+    testdir.makepyfile(
+        """
+        def test_func():
+            pass
+    """
+    )
+    res = testdir.runpytest_subprocess()
+    assert res.ret == 0
+    res.stderr.fnmatch_lines(
+        "*" + str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[0]
+    )
+
+
+def test_pytest_plugins_in_non_top_level_conftest_deprecated_no_top_level_conftest(
+    testdir
+):
+    from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST
+
+    subdirectory = testdir.tmpdir.join("subdirectory")
+    subdirectory.mkdir()
+    testdir.makeconftest(
+        """
+        import warnings
+        warnings.filterwarnings('always', category=DeprecationWarning)
+        pytest_plugins=['capture']
+    """
+    )
+    testdir.tmpdir.join("conftest.py").move(subdirectory.join("conftest.py"))
+
+    testdir.makepyfile(
+        """
+        def test_func():
+            pass
+    """
+    )
+
+    res = testdir.runpytest_subprocess()
+    assert res.ret == 0
+    res.stderr.fnmatch_lines(
+        "*" + str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[0]
+    )
+
+
+def test_pytest_plugins_in_non_top_level_conftest_deprecated_no_false_positives(
+    testdir
+):
+    from _pytest.deprecated import PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST
+
+    subdirectory = testdir.tmpdir.join("subdirectory")
+    subdirectory.mkdir()
+    testdir.makeconftest(
+        """
+        pass
+    """
+    )
+    testdir.tmpdir.join("conftest.py").move(subdirectory.join("conftest.py"))
+
+    testdir.makeconftest(
+        """
+        import warnings
+        warnings.filterwarnings('always', category=DeprecationWarning)
+        pytest_plugins=['capture']
+    """
+    )
+    testdir.makepyfile(
+        """
+        def test_func():
+            pass
+    """
+    )
+    res = testdir.runpytest_subprocess()
+    assert res.ret == 0
+    assert str(PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST).splitlines()[
+        0
+    ] not in res.stderr.str()
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/freeze/.gitignore
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/freeze/.gitignore
@@ -1,3 +1,3 @@
 build/
 dist/
-*.spec
\ No newline at end of file
+*.spec
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/freeze/create_executable.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/freeze/create_executable.py
@@ -1,12 +1,12 @@
 """
 Generates an executable with pytest runner embedded using PyInstaller.
 """
-if __name__ == '__main__':
+if __name__ == "__main__":
     import pytest
     import subprocess
 
     hidden = []
     for x in pytest.freeze_includes():
-        hidden.extend(['--hidden-import', x])
-    args = ['pyinstaller', '--noconfirm'] + hidden + ['runtests_script.py']
-    subprocess.check_call(' '.join(args), shell=True)
+        hidden.extend(["--hidden-import", x])
+    args = ["pyinstaller", "--noconfirm"] + hidden + ["runtests_script.py"]
+    subprocess.check_call(" ".join(args), shell=True)
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/freeze/runtests_script.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/freeze/runtests_script.py
@@ -1,9 +1,10 @@
 """
 This is the script that is actually frozen into an executable: simply executes
 py.test main().
 """
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     import sys
     import pytest
+
     sys.exit(pytest.main())
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/freeze/tests/test_trivial.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/freeze/tests/test_trivial.py
@@ -1,7 +1,6 @@
-
 def test_upper():
-    assert 'foo'.upper() == 'FOO'
+    assert "foo".upper() == "FOO"
 
 
 def test_lower():
-    assert 'FOO'.lower() == 'foo'
+    assert "FOO".lower() == "foo"
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/freeze/tox_run.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/freeze/tox_run.py
@@ -1,12 +1,12 @@
 """
 Called by tox.ini: uses the generated executable to run the tests in ./tests/
 directory.
 """
-if __name__ == '__main__':
+if __name__ == "__main__":
     import os
     import sys
 
-    executable = os.path.join(os.getcwd(), 'dist', 'runtests_script', 'runtests_script')
-    if sys.platform.startswith('win'):
-        executable += '.exe'
-    sys.exit(os.system('%s tests' % executable))
+    executable = os.path.join(os.getcwd(), "dist", "runtests_script", "runtests_script")
+    if sys.platform.startswith("win"):
+        executable += ".exe"
+    sys.exit(os.system("%s tests" % executable))
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/logging/test_fixture.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/logging/test_fixture.py
@@ -1,70 +1,119 @@
 # -*- coding: utf-8 -*-
 import logging
 
+import pytest
 
 logger = logging.getLogger(__name__)
-sublogger = logging.getLogger(__name__ + '.baz')
+sublogger = logging.getLogger(__name__ + ".baz")
 
 
 def test_fixture_help(testdir):
-    result = testdir.runpytest('--fixtures')
-    result.stdout.fnmatch_lines(['*caplog*'])
+    result = testdir.runpytest("--fixtures")
+    result.stdout.fnmatch_lines(["*caplog*"])
 
 
 def test_change_level(caplog):
     caplog.set_level(logging.INFO)
-    logger.debug('handler DEBUG level')
-    logger.info('handler INFO level')
+    logger.debug("handler DEBUG level")
+    logger.info("handler INFO level")
 
     caplog.set_level(logging.CRITICAL, logger=sublogger.name)
-    sublogger.warning('logger WARNING level')
-    sublogger.critical('logger CRITICAL level')
+    sublogger.warning("logger WARNING level")
+    sublogger.critical("logger CRITICAL level")
+
+    assert "DEBUG" not in caplog.text
+    assert "INFO" in caplog.text
+    assert "WARNING" not in caplog.text
+    assert "CRITICAL" in caplog.text
+
+
+def test_change_level_undo(testdir):
+    """Ensure that 'set_level' is undone after the end of the test"""
+    testdir.makepyfile(
+        """
+        import logging
 
-    assert 'DEBUG' not in caplog.text
-    assert 'INFO' in caplog.text
-    assert 'WARNING' not in caplog.text
-    assert 'CRITICAL' in caplog.text
+        def test1(caplog):
+            caplog.set_level(logging.INFO)
+            # using + operator here so fnmatch_lines doesn't match the code in the traceback
+            logging.info('log from ' + 'test1')
+            assert 0
+
+        def test2(caplog):
+            # using + operator here so fnmatch_lines doesn't match the code in the traceback
+            logging.info('log from ' + 'test2')
+            assert 0
+    """
+    )
+    result = testdir.runpytest_subprocess()
+    result.stdout.fnmatch_lines(["*log from test1*", "*2 failed in *"])
+    assert "log from test2" not in result.stdout.str()
 
 
 def test_with_statement(caplog):
     with caplog.at_level(logging.INFO):
-        logger.debug('handler DEBUG level')
-        logger.info('handler INFO level')
+        logger.debug("handler DEBUG level")
+        logger.info("handler INFO level")
 
         with caplog.at_level(logging.CRITICAL, logger=sublogger.name):
-            sublogger.warning('logger WARNING level')
-            sublogger.critical('logger CRITICAL level')
+            sublogger.warning("logger WARNING level")
+            sublogger.critical("logger CRITICAL level")
 
-    assert 'DEBUG' not in caplog.text
-    assert 'INFO' in caplog.text
-    assert 'WARNING' not in caplog.text
-    assert 'CRITICAL' in caplog.text
+    assert "DEBUG" not in caplog.text
+    assert "INFO" in caplog.text
+    assert "WARNING" not in caplog.text
+    assert "CRITICAL" in caplog.text
 
 
 def test_log_access(caplog):
-    logger.info('boo %s', 'arg')
-    assert caplog.records[0].levelname == 'INFO'
-    assert caplog.records[0].msg == 'boo %s'
-    assert 'boo arg' in caplog.text
+    caplog.set_level(logging.INFO)
+    logger.info("boo %s", "arg")
+    assert caplog.records[0].levelname == "INFO"
+    assert caplog.records[0].msg == "boo %s"
+    assert "boo arg" in caplog.text
 
 
 def test_record_tuples(caplog):
-    logger.info('boo %s', 'arg')
+    caplog.set_level(logging.INFO)
+    logger.info("boo %s", "arg")
 
-    assert caplog.record_tuples == [
-        (__name__, logging.INFO, 'boo arg'),
-    ]
+    assert caplog.record_tuples == [(__name__, logging.INFO, "boo arg")]
 
 
 def test_unicode(caplog):
-    logger.info(u'bū')
-    assert caplog.records[0].levelname == 'INFO'
-    assert caplog.records[0].msg == u'bū'
-    assert u'bū' in caplog.text
+    caplog.set_level(logging.INFO)
+    logger.info(u"bū")
+    assert caplog.records[0].levelname == "INFO"
+    assert caplog.records[0].msg == u"bū"
+    assert u"bū" in caplog.text
 
 
 def test_clear(caplog):
-    logger.info(u'bū')
+    caplog.set_level(logging.INFO)
+    logger.info(u"bū")
     assert len(caplog.records)
+    assert caplog.text
     caplog.clear()
     assert not len(caplog.records)
+    assert not caplog.text
+
+
+@pytest.fixture
+def logging_during_setup_and_teardown(caplog):
+    caplog.set_level("INFO")
+    logger.info("a_setup_log")
+    yield
+    logger.info("a_teardown_log")
+    assert [x.message for x in caplog.get_records("teardown")] == ["a_teardown_log"]
+
+
+def test_caplog_captures_for_all_stages(caplog, logging_during_setup_and_teardown):
+    assert not caplog.records
+    assert not caplog.get_records("call")
+    logger.info("a_call_log")
+    assert [x.message for x in caplog.get_records("call")] == ["a_call_log"]
+
+    assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
+
+    # This reachers into private API, don't use this type of thing in real tests!
+    assert set(caplog._item.catch_log_handlers.keys()) == {"setup", "call"}
new file mode 100644
--- /dev/null
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/logging/test_formatter.py
@@ -0,0 +1,37 @@
+import logging
+
+import py.io
+from _pytest.logging import ColoredLevelFormatter
+
+
+def test_coloredlogformatter():
+    logfmt = "%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s"
+
+    record = logging.LogRecord(
+        name="dummy",
+        level=logging.INFO,
+        pathname="dummypath",
+        lineno=10,
+        msg="Test Message",
+        args=(),
+        exc_info=False,
+    )
+
+    class ColorConfig(object):
+
+        class option(object):
+            pass
+
+    tw = py.io.TerminalWriter()
+    tw.hasmarkup = True
+    formatter = ColoredLevelFormatter(tw, logfmt)
+    output = formatter.format(record)
+    assert (
+        output
+        == ("dummypath                   10 " "\x1b[32mINFO    \x1b[0m Test Message")
+    )
+
+    tw.hasmarkup = False
+    formatter = ColoredLevelFormatter(tw, logfmt)
+    output = formatter.format(record)
+    assert output == ("dummypath                   10 " "INFO     Test Message")
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/logging/test_reporting.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/logging/test_reporting.py
@@ -1,398 +1,874 @@
 # -*- coding: utf-8 -*-
+import re
 import os
+
+import six
+
 import pytest
 
 
 def test_nothing_logged(testdir):
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         import sys
 
         def test_foo():
             sys.stdout.write('text going to stdout')
             sys.stderr.write('text going to stderr')
             assert False
-        ''')
+        """
+    )
     result = testdir.runpytest()
     assert result.ret == 1
-    result.stdout.fnmatch_lines(['*- Captured stdout call -*',
-                                 'text going to stdout'])
-    result.stdout.fnmatch_lines(['*- Captured stderr call -*',
-                                 'text going to stderr'])
+    result.stdout.fnmatch_lines(["*- Captured stdout call -*", "text going to stdout"])
+    result.stdout.fnmatch_lines(["*- Captured stderr call -*", "text going to stderr"])
     with pytest.raises(pytest.fail.Exception):
-        result.stdout.fnmatch_lines(['*- Captured *log call -*'])
+        result.stdout.fnmatch_lines(["*- Captured *log call -*"])
 
 
 def test_messages_logged(testdir):
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         import sys
         import logging
 
         logger = logging.getLogger(__name__)
 
         def test_foo():
             sys.stdout.write('text going to stdout')
             sys.stderr.write('text going to stderr')
             logger.info('text going to logger')
             assert False
-        ''')
-    result = testdir.runpytest()
+        """
+    )
+    result = testdir.runpytest("--log-level=INFO")
+    assert result.ret == 1
+    result.stdout.fnmatch_lines(["*- Captured *log call -*", "*text going to logger*"])
+    result.stdout.fnmatch_lines(["*- Captured stdout call -*", "text going to stdout"])
+    result.stdout.fnmatch_lines(["*- Captured stderr call -*", "text going to stderr"])
+
+
+def test_root_logger_affected(testdir):
+    testdir.makepyfile(
+        """
+        import logging
+        logger = logging.getLogger()
+        def test_foo():
+            logger.info('info text ' + 'going to logger')
+            logger.warning('warning text ' + 'going to logger')
+            logger.error('error text ' + 'going to logger')
+
+            assert 0
+    """
+    )
+    log_file = testdir.tmpdir.join("pytest.log").strpath
+    result = testdir.runpytest("--log-level=ERROR", "--log-file=pytest.log")
     assert result.ret == 1
-    result.stdout.fnmatch_lines(['*- Captured *log call -*',
-                                 '*text going to logger*'])
-    result.stdout.fnmatch_lines(['*- Captured stdout call -*',
-                                 'text going to stdout'])
-    result.stdout.fnmatch_lines(['*- Captured stderr call -*',
-                                 'text going to stderr'])
+
+    # the capture log calls in the stdout section only contain the
+    # logger.error msg, because --log-level=ERROR
+    result.stdout.fnmatch_lines(["*error text going to logger*"])
+    with pytest.raises(pytest.fail.Exception):
+        result.stdout.fnmatch_lines(["*warning text going to logger*"])
+    with pytest.raises(pytest.fail.Exception):
+        result.stdout.fnmatch_lines(["*info text going to logger*"])
+
+    # the log file should contain the warning and the error log messages and
+    # not the info one, because the default level of the root logger is
+    # WARNING.
+    assert os.path.isfile(log_file)
+    with open(log_file) as rfh:
+        contents = rfh.read()
+        assert "info text going to logger" not in contents
+        assert "warning text going to logger" in contents
+        assert "error text going to logger" in contents
+
+
+def test_log_cli_level_log_level_interaction(testdir):
+    testdir.makepyfile(
+        """
+        import logging
+        logger = logging.getLogger()
+
+        def test_foo():
+            logger.debug('debug text ' + 'going to logger')
+            logger.info('info text ' + 'going to logger')
+            logger.warning('warning text ' + 'going to logger')
+            logger.error('error text ' + 'going to logger')
+            assert 0
+    """
+    )
+
+    result = testdir.runpytest("--log-cli-level=INFO", "--log-level=ERROR")
+    assert result.ret == 1
+
+    result.stdout.fnmatch_lines(
+        [
+            "*-- live log call --*",
+            "*INFO*info text going to logger",
+            "*WARNING*warning text going to logger",
+            "*ERROR*error text going to logger",
+            "=* 1 failed in *=",
+        ]
+    )
+    assert "DEBUG" not in result.stdout.str()
 
 
 def test_setup_logging(testdir):
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         import logging
 
         logger = logging.getLogger(__name__)
 
         def setup_function(function):
             logger.info('text going to logger from setup')
 
         def test_foo():
             logger.info('text going to logger from call')
             assert False
-        ''')
-    result = testdir.runpytest()
+    """
+    )
+    result = testdir.runpytest("--log-level=INFO")
     assert result.ret == 1
-    result.stdout.fnmatch_lines(['*- Captured *log setup -*',
-                                 '*text going to logger from setup*',
-                                 '*- Captured *log call -*',
-                                 '*text going to logger from call*'])
+    result.stdout.fnmatch_lines(
+        [
+            "*- Captured *log setup -*",
+            "*text going to logger from setup*",
+            "*- Captured *log call -*",
+            "*text going to logger from call*",
+        ]
+    )
 
 
 def test_teardown_logging(testdir):
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         import logging
 
         logger = logging.getLogger(__name__)
 
         def test_foo():
             logger.info('text going to logger from call')
 
         def teardown_function(function):
             logger.info('text going to logger from teardown')
             assert False
-        ''')
-    result = testdir.runpytest()
+        """
+    )
+    result = testdir.runpytest("--log-level=INFO")
     assert result.ret == 1
-    result.stdout.fnmatch_lines(['*- Captured *log call -*',
-                                 '*text going to logger from call*',
-                                 '*- Captured *log teardown -*',
-                                 '*text going to logger from teardown*'])
+    result.stdout.fnmatch_lines(
+        [
+            "*- Captured *log call -*",
+            "*text going to logger from call*",
+            "*- Captured *log teardown -*",
+            "*text going to logger from teardown*",
+        ]
+    )
 
 
 def test_disable_log_capturing(testdir):
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         import sys
         import logging
 
         logger = logging.getLogger(__name__)
 
         def test_foo():
             sys.stdout.write('text going to stdout')
             logger.warning('catch me if you can!')
             sys.stderr.write('text going to stderr')
             assert False
-        ''')
-    result = testdir.runpytest('--no-print-logs')
+        """
+    )
+    result = testdir.runpytest("--no-print-logs")
     print(result.stdout)
     assert result.ret == 1
-    result.stdout.fnmatch_lines(['*- Captured stdout call -*',
-                                 'text going to stdout'])
-    result.stdout.fnmatch_lines(['*- Captured stderr call -*',
-                                 'text going to stderr'])
+    result.stdout.fnmatch_lines(["*- Captured stdout call -*", "text going to stdout"])
+    result.stdout.fnmatch_lines(["*- Captured stderr call -*", "text going to stderr"])
     with pytest.raises(pytest.fail.Exception):
-        result.stdout.fnmatch_lines(['*- Captured *log call -*'])
+        result.stdout.fnmatch_lines(["*- Captured *log call -*"])
 
 
 def test_disable_log_capturing_ini(testdir):
     testdir.makeini(
-        '''
+        """
         [pytest]
         log_print=False
-        '''
+        """
     )
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         import sys
         import logging
 
         logger = logging.getLogger(__name__)
 
         def test_foo():
             sys.stdout.write('text going to stdout')
             logger.warning('catch me if you can!')
             sys.stderr.write('text going to stderr')
             assert False
-        ''')
+        """
+    )
     result = testdir.runpytest()
     print(result.stdout)
     assert result.ret == 1
-    result.stdout.fnmatch_lines(['*- Captured stdout call -*',
-                                 'text going to stdout'])
-    result.stdout.fnmatch_lines(['*- Captured stderr call -*',
-                                 'text going to stderr'])
+    result.stdout.fnmatch_lines(["*- Captured stdout call -*", "text going to stdout"])
+    result.stdout.fnmatch_lines(["*- Captured stderr call -*", "text going to stderr"])
     with pytest.raises(pytest.fail.Exception):
-        result.stdout.fnmatch_lines(['*- Captured *log call -*'])
+        result.stdout.fnmatch_lines(["*- Captured *log call -*"])
+
+
+@pytest.mark.parametrize("enabled", [True, False])
+def test_log_cli_enabled_disabled(testdir, enabled):
+    msg = "critical message logged by test"
+    testdir.makepyfile(
+        """
+        import logging
+        def test_log_cli():
+            logging.critical("{}")
+    """.format(
+            msg
+        )
+    )
+    if enabled:
+        testdir.makeini(
+            """
+            [pytest]
+            log_cli=true
+        """
+        )
+    result = testdir.runpytest()
+    if enabled:
+        result.stdout.fnmatch_lines(
+            [
+                "test_log_cli_enabled_disabled.py::test_log_cli ",
+                "*-- live log call --*",
+                "test_log_cli_enabled_disabled.py* CRITICAL critical message logged by test",
+                "PASSED*",
+            ]
+        )
+    else:
+        assert msg not in result.stdout.str()
 
 
 def test_log_cli_default_level(testdir):
     # Default log file level
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         import pytest
         import logging
         def test_log_cli(request):
             plugin = request.config.pluginmanager.getplugin('logging-plugin')
-            assert plugin.log_cli_handler.level == logging.WARNING
-            logging.getLogger('catchlog').info("This log message won't be shown")
-            logging.getLogger('catchlog').warning("This log message will be shown")
-            print('PASSED')
-    ''')
+            assert plugin.log_cli_handler.level == logging.NOTSET
+            logging.getLogger('catchlog').info("INFO message won't be shown")
+            logging.getLogger('catchlog').warning("WARNING message will be shown")
+    """
+    )
+    testdir.makeini(
+        """
+        [pytest]
+        log_cli=true
+    """
+    )
 
-    result = testdir.runpytest('-s')
+    result = testdir.runpytest()
 
     # fnmatch_lines does an assertion internally
-    result.stdout.fnmatch_lines([
-        'test_log_cli_default_level.py PASSED',
-    ])
-    result.stderr.fnmatch_lines([
-        "* This log message will be shown"
-    ])
-    for line in result.errlines:
-        try:
-            assert "This log message won't be shown" in line
-            pytest.fail("A log message was shown and it shouldn't have been")
-        except AssertionError:
-            continue
-
+    result.stdout.fnmatch_lines(
+        [
+            "test_log_cli_default_level.py::test_log_cli ",
+            "test_log_cli_default_level.py*WARNING message will be shown*",
+        ]
+    )
+    assert "INFO message won't be shown" not in result.stdout.str()
     # make sure that that we get a '0' exit code for the testsuite
     assert result.ret == 0
 
 
+def test_log_cli_default_level_multiple_tests(testdir, request):
+    """Ensure we reset the first newline added by the live logger between tests"""
+    filename = request.node.name + ".py"
+    testdir.makepyfile(
+        """
+        import logging
+
+        def test_log_1():
+            logging.warning("log message from test_log_1")
+
+        def test_log_2():
+            logging.warning("log message from test_log_2")
+    """
+    )
+    testdir.makeini(
+        """
+        [pytest]
+        log_cli=true
+    """
+    )
+
+    result = testdir.runpytest()
+    result.stdout.fnmatch_lines(
+        [
+            "{}::test_log_1 ".format(filename),
+            "*WARNING*log message from test_log_1*",
+            "PASSED *50%*",
+            "{}::test_log_2 ".format(filename),
+            "*WARNING*log message from test_log_2*",
+            "PASSED *100%*",
+            "=* 2 passed in *=",
+        ]
+    )
+
+
+def test_log_cli_default_level_sections(testdir, request):
+    """Check that with live logging enable we are printing the correct headers during
+    start/setup/call/teardown/finish."""
+    filename = request.node.name + ".py"
+    testdir.makeconftest(
+        """
+        import pytest
+        import logging
+
+        def pytest_runtest_logstart():
+            logging.warning('>>>>> START >>>>>')
+
+        def pytest_runtest_logfinish():
+            logging.warning('<<<<< END <<<<<<<')
+    """
+    )
+
+    testdir.makepyfile(
+        """
+        import pytest
+        import logging
+
+        @pytest.fixture
+        def fix(request):
+            logging.warning("log message from setup of {}".format(request.node.name))
+            yield
+            logging.warning("log message from teardown of {}".format(request.node.name))
+
+        def test_log_1(fix):
+            logging.warning("log message from test_log_1")
+
+        def test_log_2(fix):
+            logging.warning("log message from test_log_2")
+    """
+    )
+    testdir.makeini(
+        """
+        [pytest]
+        log_cli=true
+    """
+    )
+
+    result = testdir.runpytest()
+    result.stdout.fnmatch_lines(
+        [
+            "{}::test_log_1 ".format(filename),
+            "*-- live log start --*",
+            "*WARNING* >>>>> START >>>>>*",
+            "*-- live log setup --*",
+            "*WARNING*log message from setup of test_log_1*",
+            "*-- live log call --*",
+            "*WARNING*log message from test_log_1*",
+            "PASSED *50%*",
+            "*-- live log teardown --*",
+            "*WARNING*log message from teardown of test_log_1*",
+            "*-- live log finish --*",
+            "*WARNING* <<<<< END <<<<<<<*",
+            "{}::test_log_2 ".format(filename),
+            "*-- live log start --*",
+            "*WARNING* >>>>> START >>>>>*",
+            "*-- live log setup --*",
+            "*WARNING*log message from setup of test_log_2*",
+            "*-- live log call --*",
+            "*WARNING*log message from test_log_2*",
+            "PASSED *100%*",
+            "*-- live log teardown --*",
+            "*WARNING*log message from teardown of test_log_2*",
+            "*-- live log finish --*",
+            "*WARNING* <<<<< END <<<<<<<*",
+            "=* 2 passed in *=",
+        ]
+    )
+
+
+def test_live_logs_unknown_sections(testdir, request):
+    """Check that with live logging enable we are printing the correct headers during
+    start/setup/call/teardown/finish."""
+    filename = request.node.name + ".py"
+    testdir.makeconftest(
+        """
+        import pytest
+        import logging
+
+        def pytest_runtest_protocol(item, nextitem):
+            logging.warning('Unknown Section!')
+
+        def pytest_runtest_logstart():
+            logging.warning('>>>>> START >>>>>')
+
+        def pytest_runtest_logfinish():
+            logging.warning('<<<<< END <<<<<<<')
+    """
+    )
+
+    testdir.makepyfile(
+        """
+        import pytest
+        import logging
+
+        @pytest.fixture
+        def fix(request):
+            logging.warning("log message from setup of {}".format(request.node.name))
+            yield
+            logging.warning("log message from teardown of {}".format(request.node.name))
+
+        def test_log_1(fix):
+            logging.warning("log message from test_log_1")
+
+    """
+    )
+    testdir.makeini(
+        """
+        [pytest]
+        log_cli=true
+    """
+    )
+
+    result = testdir.runpytest()
+    result.stdout.fnmatch_lines(
+        [
+            "*WARNING*Unknown Section*",
+            "{}::test_log_1 ".format(filename),
+            "*WARNING* >>>>> START >>>>>*",
+            "*-- live log setup --*",
+            "*WARNING*log message from setup of test_log_1*",
+            "*-- live log call --*",
+            "*WARNING*log message from test_log_1*",
+            "PASSED *100%*",
+            "*-- live log teardown --*",
+            "*WARNING*log message from teardown of test_log_1*",
+            "*WARNING* <<<<< END <<<<<<<*",
+            "=* 1 passed in *=",
+        ]
+    )
+
+
+def test_sections_single_new_line_after_test_outcome(testdir, request):
+    """Check that only a single new line is written between log messages during
+    teardown/finish."""
+    filename = request.node.name + ".py"
+    testdir.makeconftest(
+        """
+        import pytest
+        import logging
+
+        def pytest_runtest_logstart():
+            logging.warning('>>>>> START >>>>>')
+
+        def pytest_runtest_logfinish():
+            logging.warning('<<<<< END <<<<<<<')
+            logging.warning('<<<<< END <<<<<<<')
+    """
+    )
+
+    testdir.makepyfile(
+        """
+        import pytest
+        import logging
+
+        @pytest.fixture
+        def fix(request):
+            logging.warning("log message from setup of {}".format(request.node.name))
+            yield
+            logging.warning("log message from teardown of {}".format(request.node.name))
+            logging.warning("log message from teardown of {}".format(request.node.name))
+
+        def test_log_1(fix):
+            logging.warning("log message from test_log_1")
+    """
+    )
+    testdir.makeini(
+        """
+        [pytest]
+        log_cli=true
+    """
+    )
+
+    result = testdir.runpytest()
+    result.stdout.fnmatch_lines(
+        [
+            "{}::test_log_1 ".format(filename),
+            "*-- live log start --*",
+            "*WARNING* >>>>> START >>>>>*",
+            "*-- live log setup --*",
+            "*WARNING*log message from setup of test_log_1*",
+            "*-- live log call --*",
+            "*WARNING*log message from test_log_1*",
+            "PASSED *100%*",
+            "*-- live log teardown --*",
+            "*WARNING*log message from teardown of test_log_1*",
+            "*-- live log finish --*",
+            "*WARNING* <<<<< END <<<<<<<*",
+            "*WARNING* <<<<< END <<<<<<<*",
+            "=* 1 passed in *=",
+        ]
+    )
+    assert re.search(
+        r"(.+)live log teardown(.+)\n(.+)WARNING(.+)\n(.+)WARNING(.+)",
+        result.stdout.str(),
+        re.MULTILINE,
+    ) is not None
+    assert re.search(
+        r"(.+)live log finish(.+)\n(.+)WARNING(.+)\n(.+)WARNING(.+)",
+        result.stdout.str(),
+        re.MULTILINE,
+    ) is not None
+
+
 def test_log_cli_level(testdir):
     # Default log file level
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         import pytest
         import logging
         def test_log_cli(request):
             plugin = request.config.pluginmanager.getplugin('logging-plugin')
             assert plugin.log_cli_handler.level == logging.INFO
             logging.getLogger('catchlog').debug("This log message won't be shown")
             logging.getLogger('catchlog').info("This log message will be shown")
             print('PASSED')
-    ''')
+    """
+    )
+    testdir.makeini(
+        """
+        [pytest]
+        log_cli=true
+    """
+    )
 
-    result = testdir.runpytest('-s', '--log-cli-level=INFO')
+    result = testdir.runpytest("-s", "--log-cli-level=INFO")
 
     # fnmatch_lines does an assertion internally
-    result.stdout.fnmatch_lines([
-        'test_log_cli_level.py PASSED',
-    ])
-    result.stderr.fnmatch_lines([
-        "* This log message will be shown"
-    ])
-    for line in result.errlines:
-        try:
-            assert "This log message won't be shown" in line
-            pytest.fail("A log message was shown and it shouldn't have been")
-        except AssertionError:
-            continue
+    result.stdout.fnmatch_lines(
+        [
+            "test_log_cli_level.py*This log message will be shown",
+            "PASSED",  # 'PASSED' on its own line because the log message prints a new line
+        ]
+    )
+    assert "This log message won't be shown" not in result.stdout.str()
 
     # make sure that that we get a '0' exit code for the testsuite
     assert result.ret == 0
 
-    result = testdir.runpytest('-s', '--log-level=INFO')
+    result = testdir.runpytest("-s", "--log-level=INFO")
 
     # fnmatch_lines does an assertion internally
-    result.stdout.fnmatch_lines([
-        'test_log_cli_level.py PASSED',
-    ])
-    result.stderr.fnmatch_lines([
-        "* This log message will be shown"
-    ])
-    for line in result.errlines:
-        try:
-            assert "This log message won't be shown" in line
-            pytest.fail("A log message was shown and it shouldn't have been")
-        except AssertionError:
-            continue
+    result.stdout.fnmatch_lines(
+        [
+            "test_log_cli_level.py* This log message will be shown",
+            "PASSED",  # 'PASSED' on its own line because the log message prints a new line
+        ]
+    )
+    assert "This log message won't be shown" not in result.stdout.str()
 
     # make sure that that we get a '0' exit code for the testsuite
     assert result.ret == 0
 
 
 def test_log_cli_ini_level(testdir):
     testdir.makeini(
         """
         [pytest]
+        log_cli=true
         log_cli_level = INFO
-        """)
-    testdir.makepyfile('''
+        """
+    )
+    testdir.makepyfile(
+        """
         import pytest
         import logging
         def test_log_cli(request):
             plugin = request.config.pluginmanager.getplugin('logging-plugin')
             assert plugin.log_cli_handler.level == logging.INFO
             logging.getLogger('catchlog').debug("This log message won't be shown")
             logging.getLogger('catchlog').info("This log message will be shown")
             print('PASSED')
-    ''')
+    """
+    )
 
-    result = testdir.runpytest('-s')
+    result = testdir.runpytest("-s")
 
     # fnmatch_lines does an assertion internally
-    result.stdout.fnmatch_lines([
-        'test_log_cli_ini_level.py PASSED',
-    ])
-    result.stderr.fnmatch_lines([
-        "* This log message will be shown"
-    ])
-    for line in result.errlines:
-        try:
-            assert "This log message won't be shown" in line
-            pytest.fail("A log message was shown and it shouldn't have been")
-        except AssertionError:
-            continue
+    result.stdout.fnmatch_lines(
+        [
+            "test_log_cli_ini_level.py* This log message will be shown",
+            "PASSED",  # 'PASSED' on its own line because the log message prints a new line
+        ]
+    )
+    assert "This log message won't be shown" not in result.stdout.str()
 
     # make sure that that we get a '0' exit code for the testsuite
     assert result.ret == 0
 
 
+@pytest.mark.parametrize(
+    "cli_args",
+    ["", "--log-level=WARNING", "--log-file-level=WARNING", "--log-cli-level=WARNING"],
+)
+def test_log_cli_auto_enable(testdir, request, cli_args):
+    """Check that live logs are enabled if --log-level or --log-cli-level is passed on the CLI.
+    It should not be auto enabled if the same configs are set on the INI file.
+    """
+    testdir.makepyfile(
+        """
+        import pytest
+        import logging
+
+        def test_log_1():
+            logging.info("log message from test_log_1 not to be shown")
+            logging.warning("log message from test_log_1")
+
+    """
+    )
+    testdir.makeini(
+        """
+        [pytest]
+        log_level=INFO
+        log_cli_level=INFO
+    """
+    )
+
+    result = testdir.runpytest(cli_args)
+    if cli_args == "--log-cli-level=WARNING":
+        result.stdout.fnmatch_lines(
+            [
+                "*::test_log_1 ",
+                "*-- live log call --*",
+                "*WARNING*log message from test_log_1*",
+                "PASSED *100%*",
+                "=* 1 passed in *=",
+            ]
+        )
+        assert "INFO" not in result.stdout.str()
+    else:
+        result.stdout.fnmatch_lines(
+            ["*test_log_cli_auto_enable*100%*", "=* 1 passed in *="]
+        )
+        assert "INFO" not in result.stdout.str()
+        assert "WARNING" not in result.stdout.str()
+
+
 def test_log_file_cli(testdir):
     # Default log file level
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         import pytest
         import logging
         def test_log_file(request):
             plugin = request.config.pluginmanager.getplugin('logging-plugin')
             assert plugin.log_file_handler.level == logging.WARNING
             logging.getLogger('catchlog').info("This log message won't be shown")
             logging.getLogger('catchlog').warning("This log message will be shown")
             print('PASSED')
-    ''')
+    """
+    )
 
-    log_file = testdir.tmpdir.join('pytest.log').strpath
+    log_file = testdir.tmpdir.join("pytest.log").strpath
 
-    result = testdir.runpytest('-s', '--log-file={0}'.format(log_file))
+    result = testdir.runpytest(
+        "-s", "--log-file={}".format(log_file), "--log-file-level=WARNING"
+    )
 
     # fnmatch_lines does an assertion internally
-    result.stdout.fnmatch_lines([
-        'test_log_file_cli.py PASSED',
-    ])
+    result.stdout.fnmatch_lines(["test_log_file_cli.py PASSED"])
 
     # make sure that that we get a '0' exit code for the testsuite
     assert result.ret == 0
     assert os.path.isfile(log_file)
     with open(log_file) as rfh:
         contents = rfh.read()
         assert "This log message will be shown" in contents
         assert "This log message won't be shown" not in contents
 
 
 def test_log_file_cli_level(testdir):
     # Default log file level
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         import pytest
         import logging
         def test_log_file(request):
             plugin = request.config.pluginmanager.getplugin('logging-plugin')
             assert plugin.log_file_handler.level == logging.INFO
             logging.getLogger('catchlog').debug("This log message won't be shown")
             logging.getLogger('catchlog').info("This log message will be shown")
             print('PASSED')
-    ''')
-
-    log_file = testdir.tmpdir.join('pytest.log').strpath
+    """
+    )
 
-    result = testdir.runpytest('-s',
-                               '--log-file={0}'.format(log_file),
-                               '--log-file-level=INFO')
+    log_file = testdir.tmpdir.join("pytest.log").strpath
+
+    result = testdir.runpytest(
+        "-s", "--log-file={}".format(log_file), "--log-file-level=INFO"
+    )
 
     # fnmatch_lines does an assertion internally
-    result.stdout.fnmatch_lines([
-        'test_log_file_cli_level.py PASSED',
-    ])
+    result.stdout.fnmatch_lines(["test_log_file_cli_level.py PASSED"])
 
     # make sure that that we get a '0' exit code for the testsuite
     assert result.ret == 0
     assert os.path.isfile(log_file)
     with open(log_file) as rfh:
         contents = rfh.read()
         assert "This log message will be shown" in contents
         assert "This log message won't be shown" not in contents
 
 
+def test_log_level_not_changed_by_default(testdir):
+    testdir.makepyfile(
+        """
+        import logging
+        def test_log_file():
+            assert logging.getLogger().level == logging.WARNING
+    """
+    )
+    result = testdir.runpytest("-s")
+    result.stdout.fnmatch_lines("* 1 passed in *")
+
+
 def test_log_file_ini(testdir):
-    log_file = testdir.tmpdir.join('pytest.log').strpath
+    log_file = testdir.tmpdir.join("pytest.log").strpath
 
     testdir.makeini(
         """
         [pytest]
-        log_file={0}
-        """.format(log_file))
-    testdir.makepyfile('''
+        log_file={}
+        log_file_level=WARNING
+        """.format(
+            log_file
+        )
+    )
+    testdir.makepyfile(
+        """
         import pytest
         import logging
         def test_log_file(request):
             plugin = request.config.pluginmanager.getplugin('logging-plugin')
             assert plugin.log_file_handler.level == logging.WARNING
             logging.getLogger('catchlog').info("This log message won't be shown")
             logging.getLogger('catchlog').warning("This log message will be shown")
             print('PASSED')
-    ''')
+    """
+    )
 
-    result = testdir.runpytest('-s')
+    result = testdir.runpytest("-s")
 
     # fnmatch_lines does an assertion internally
-    result.stdout.fnmatch_lines([
-        'test_log_file_ini.py PASSED',
-    ])
+    result.stdout.fnmatch_lines(["test_log_file_ini.py PASSED"])
 
     # make sure that that we get a '0' exit code for the testsuite
     assert result.ret == 0
     assert os.path.isfile(log_file)
     with open(log_file) as rfh:
         contents = rfh.read()
         assert "This log message will be shown" in contents
         assert "This log message won't be shown" not in contents
 
 
 def test_log_file_ini_level(testdir):
-    log_file = testdir.tmpdir.join('pytest.log').strpath
+    log_file = testdir.tmpdir.join("pytest.log").strpath
 
     testdir.makeini(
         """
         [pytest]
-        log_file={0}
+        log_file={}
         log_file_level = INFO
-        """.format(log_file))
-    testdir.makepyfile('''
+        """.format(
+            log_file
+        )
+    )
+    testdir.makepyfile(
+        """
         import pytest
         import logging
         def test_log_file(request):
             plugin = request.config.pluginmanager.getplugin('logging-plugin')
             assert plugin.log_file_handler.level == logging.INFO
             logging.getLogger('catchlog').debug("This log message won't be shown")
             logging.getLogger('catchlog').info("This log message will be shown")
             print('PASSED')
-    ''')
+    """
+    )
 
-    result = testdir.runpytest('-s')
+    result = testdir.runpytest("-s")
 
     # fnmatch_lines does an assertion internally
-    result.stdout.fnmatch_lines([
-        'test_log_file_ini_level.py PASSED',
-    ])
+    result.stdout.fnmatch_lines(["test_log_file_ini_level.py PASSED"])
 
     # make sure that that we get a '0' exit code for the testsuite
     assert result.ret == 0
     assert os.path.isfile(log_file)
     with open(log_file) as rfh:
         contents = rfh.read()
         assert "This log message will be shown" in contents
         assert "This log message won't be shown" not in contents
+
+
+@pytest.mark.parametrize("has_capture_manager", [True, False])
+def test_live_logging_suspends_capture(has_capture_manager, request):
+    """Test that capture manager is suspended when we emitting messages for live logging.
+
+    This tests the implementation calls instead of behavior because it is difficult/impossible to do it using
+    ``testdir`` facilities because they do their own capturing.
+
+    We parametrize the test to also make sure _LiveLoggingStreamHandler works correctly if no capture manager plugin
+    is installed.
+    """
+    import logging
+    from functools import partial
+    from _pytest.capture import CaptureManager
+    from _pytest.logging import _LiveLoggingStreamHandler
+
+    class MockCaptureManager:
+        calls = []
+
+        def suspend_global_capture(self):
+            self.calls.append("suspend_global_capture")
+
+        def resume_global_capture(self):
+            self.calls.append("resume_global_capture")
+
+    # sanity check
+    assert CaptureManager.suspend_capture_item
+    assert CaptureManager.resume_global_capture
+
+    class DummyTerminal(six.StringIO):
+
+        def section(self, *args, **kwargs):
+            pass
+
+    out_file = DummyTerminal()
+    capture_manager = MockCaptureManager() if has_capture_manager else None
+    handler = _LiveLoggingStreamHandler(out_file, capture_manager)
+    handler.set_when("call")
+
+    logger = logging.getLogger(__name__ + ".test_live_logging_suspends_capture")
+    logger.addHandler(handler)
+    request.addfinalizer(partial(logger.removeHandler, handler))
+
+    logger.critical("some message")
+    if has_capture_manager:
+        assert (
+            MockCaptureManager.calls
+            == ["suspend_global_capture", "resume_global_capture"]
+        )
+    else:
+        assert MockCaptureManager.calls == []
+    assert out_file.getvalue() == "\nsome message\n"
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/python/approx.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/python/approx.py
@@ -3,83 +3,96 @@ import operator
 import sys
 import pytest
 import doctest
 
 from pytest import approx
 from operator import eq, ne
 from decimal import Decimal
 from fractions import Fraction
-inf, nan = float('inf'), float('nan')
+
+inf, nan = float("inf"), float("nan")
 
 
 class MyDocTestRunner(doctest.DocTestRunner):
 
     def __init__(self):
         doctest.DocTestRunner.__init__(self)
 
     def report_failure(self, out, test, example, got):
-        raise AssertionError("'{}' evaluates to '{}', not '{}'".format(
-            example.source.strip(), got.strip(), example.want.strip()))
+        raise AssertionError(
+            "'{}' evaluates to '{}', not '{}'".format(
+                example.source.strip(), got.strip(), example.want.strip()
+            )
+        )
 
 
 class TestApprox(object):
 
     def test_repr_string(self):
-        plus_minus = u'\u00b1' if sys.version_info[0] > 2 else u'+-'
-        tol1, tol2, infr = '1.0e-06', '2.0e-06', 'inf'
-        assert repr(approx(1.0)) == '1.0 {pm} {tol1}'.format(pm=plus_minus, tol1=tol1)
-        assert repr(approx([1.0, 2.0])) == 'approx([1.0 {pm} {tol1}, 2.0 {pm} {tol2}])'.format(
-            pm=plus_minus, tol1=tol1, tol2=tol2)
-        assert repr(approx((1.0, 2.0))) == 'approx((1.0 {pm} {tol1}, 2.0 {pm} {tol2}))'.format(
-            pm=plus_minus, tol1=tol1, tol2=tol2)
-        assert repr(approx(inf)) == 'inf'
-        assert repr(approx(1.0, rel=nan)) == '1.0 {pm} ???'.format(pm=plus_minus)
-        assert repr(approx(1.0, rel=inf)) == '1.0 {pm} {infr}'.format(pm=plus_minus, infr=infr)
-        assert repr(approx(1.0j, rel=inf)) == '1j'
+        plus_minus = u"\u00b1" if sys.version_info[0] > 2 else u"+-"
+        tol1, tol2, infr = "1.0e-06", "2.0e-06", "inf"
+        assert repr(approx(1.0)) == "1.0 {pm} {tol1}".format(pm=plus_minus, tol1=tol1)
+        assert (
+            repr(approx([1.0, 2.0]))
+            == "approx([1.0 {pm} {tol1}, 2.0 {pm} {tol2}])".format(
+                pm=plus_minus, tol1=tol1, tol2=tol2
+            )
+        )
+        assert (
+            repr(approx((1.0, 2.0)))
+            == "approx((1.0 {pm} {tol1}, 2.0 {pm} {tol2}))".format(
+                pm=plus_minus, tol1=tol1, tol2=tol2
+            )
+        )
+        assert repr(approx(inf)) == "inf"
+        assert repr(approx(1.0, rel=nan)) == "1.0 {pm} ???".format(pm=plus_minus)
+        assert (
+            repr(approx(1.0, rel=inf))
+            == "1.0 {pm} {infr}".format(pm=plus_minus, infr=infr)
+        )
+        assert repr(approx(1.0j, rel=inf)) == "1j"
 
         # Dictionaries aren't ordered, so we need to check both orders.
-        assert repr(approx({'a': 1.0, 'b': 2.0})) in (
-            "approx({{'a': 1.0 {pm} {tol1}, 'b': 2.0 {pm} {tol2}}})".format(pm=plus_minus, tol1=tol1, tol2=tol2),
-            "approx({{'b': 2.0 {pm} {tol2}, 'a': 1.0 {pm} {tol1}}})".format(pm=plus_minus, tol1=tol1, tol2=tol2),
+        assert repr(approx({"a": 1.0, "b": 2.0})) in (
+            "approx({{'a': 1.0 {pm} {tol1}, 'b': 2.0 {pm} {tol2}}})".format(
+                pm=plus_minus, tol1=tol1, tol2=tol2
+            ),
+            "approx({{'b': 2.0 {pm} {tol2}, 'a': 1.0 {pm} {tol1}}})".format(
+                pm=plus_minus, tol1=tol1, tol2=tol2
+            ),
         )
 
     def test_operator_overloading(self):
         assert 1 == approx(1, rel=1e-6, abs=1e-12)
         assert not (1 != approx(1, rel=1e-6, abs=1e-12))
         assert 10 != approx(1, rel=1e-6, abs=1e-12)
         assert not (10 == approx(1, rel=1e-6, abs=1e-12))
 
     def test_exactly_equal(self):
         examples = [
             (2.0, 2.0),
             (0.1e200, 0.1e200),
             (1.123e-300, 1.123e-300),
             (12345, 12345.0),
             (0.0, -0.0),
             (345678, 345678),
-            (Decimal('1.0001'), Decimal('1.0001')),
+            (Decimal("1.0001"), Decimal("1.0001")),
             (Fraction(1, 3), Fraction(-1, -3)),
         ]
         for a, x in examples:
             assert a == approx(x)
 
     def test_opposite_sign(self):
-        examples = [
-            (eq, 1e-100, -1e-100),
-            (ne, 1e100, -1e100),
-        ]
+        examples = [(eq, 1e-100, -1e-100), (ne, 1e100, -1e100)]
         for op, a, x in examples:
             assert op(a, approx(x))
 
     def test_zero_tolerance(self):
-        within_1e10 = [
-            (1.1e-100, 1e-100),
-            (-1.1e-100, -1e-100),
-        ]
+        within_1e10 = [(1.1e-100, 1e-100), (-1.1e-100, -1e-100)]
         for a, x in within_1e10:
             assert x == approx(x, rel=0.0, abs=0.0)
             assert a != approx(x, rel=0.0, abs=0.0)
             assert a == approx(x, rel=0.0, abs=5e-101)
             assert a != approx(x, rel=0.0, abs=5e-102)
             assert a == approx(x, rel=5e-1, abs=0.0)
             assert a != approx(x, rel=5e-2, abs=0.0)
 
@@ -93,45 +106,33 @@ class TestApprox(object):
             dict(rel=-1e100, abs=-1e100),
         ]
         for kwargs in illegal_kwargs:
             with pytest.raises(ValueError):
                 1.1 == approx(1, **kwargs)
 
     def test_inf_tolerance(self):
         # Everything should be equal if the tolerance is infinite.
-        large_diffs = [
-            (1, 1000),
-            (1e-50, 1e50),
-            (-1.0, -1e300),
-            (0.0, 10),
-        ]
+        large_diffs = [(1, 1000), (1e-50, 1e50), (-1.0, -1e300), (0.0, 10)]
         for a, x in large_diffs:
             assert a != approx(x, rel=0.0, abs=0.0)
             assert a == approx(x, rel=inf, abs=0.0)
             assert a == approx(x, rel=0.0, abs=inf)
             assert a == approx(x, rel=inf, abs=inf)
 
     def test_inf_tolerance_expecting_zero(self):
         # If the relative tolerance is zero but the expected value is infinite,
         # the actual tolerance is a NaN, which should be an error.
-        illegal_kwargs = [
-            dict(rel=inf, abs=0.0),
-            dict(rel=inf, abs=inf),
-        ]
+        illegal_kwargs = [dict(rel=inf, abs=0.0), dict(rel=inf, abs=inf)]
         for kwargs in illegal_kwargs:
             with pytest.raises(ValueError):
                 1 == approx(0, **kwargs)
 
     def test_nan_tolerance(self):
-        illegal_kwargs = [
-            dict(rel=nan),
-            dict(abs=nan),
-            dict(rel=nan, abs=nan),
-        ]
+        illegal_kwargs = [dict(rel=nan), dict(abs=nan), dict(rel=nan, abs=nan)]
         for kwargs in illegal_kwargs:
             with pytest.raises(ValueError):
                 1.1 == approx(1, **kwargs)
 
     def test_reasonable_defaults(self):
         # Whatever the defaults are, they should work for numbers close to 1
         # than have a small amount of floating-point error.
         assert 0.1 + 0.2 == approx(0.3)
@@ -143,18 +144,18 @@ class TestApprox(object):
         # the choice of defaults.
         examples = [
             # Relative tolerance used.
             (eq, 1e100 + 1e94, 1e100),
             (ne, 1e100 + 2e94, 1e100),
             (eq, 1e0 + 1e-6, 1e0),
             (ne, 1e0 + 2e-6, 1e0),
             # Absolute tolerance used.
-            (eq, 1e-100, + 1e-106),
-            (eq, 1e-100, + 2e-106),
+            (eq, 1e-100, +1e-106),
+            (eq, 1e-100, +2e-106),
             (eq, 1e-100, 0),
         ]
         for op, a, x in examples:
             assert op(a, approx(x))
 
     def test_custom_tolerances(self):
         assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e0)
         assert 1e8 + 1e0 == approx(1e8, rel=5e-9, abs=5e0)
@@ -167,31 +168,23 @@ class TestApprox(object):
         assert 1e0 + 1e-8 != approx(1e0, rel=5e-9, abs=5e-9)
 
         assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-16)
         assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-9, abs=5e-16)
         assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-17)
         assert 1e-8 + 1e-16 != approx(1e-8, rel=5e-9, abs=5e-17)
 
     def test_relative_tolerance(self):
-        within_1e8_rel = [
-            (1e8 + 1e0, 1e8),
-            (1e0 + 1e-8, 1e0),
-            (1e-8 + 1e-16, 1e-8),
-        ]
+        within_1e8_rel = [(1e8 + 1e0, 1e8), (1e0 + 1e-8, 1e0), (1e-8 + 1e-16, 1e-8)]
         for a, x in within_1e8_rel:
             assert a == approx(x, rel=5e-8, abs=0.0)
             assert a != approx(x, rel=5e-9, abs=0.0)
 
     def test_absolute_tolerance(self):
-        within_1e8_abs = [
-            (1e8 + 9e-9, 1e8),
-            (1e0 + 9e-9, 1e0),
-            (1e-8 + 9e-9, 1e-8),
-        ]
+        within_1e8_abs = [(1e8 + 9e-9, 1e8), (1e0 + 9e-9, 1e0), (1e-8 + 9e-9, 1e-8)]
         for a, x in within_1e8_abs:
             assert a == approx(x, rel=0, abs=5e-8)
             assert a != approx(x, rel=0, abs=5e-9)
 
     def test_expecting_zero(self):
         examples = [
             (ne, 1e-6, 0.0),
             (ne, -1e-6, 0.0),
@@ -228,36 +221,34 @@ class TestApprox(object):
         for op, a, x in examples:
             # Nothing is equal to NaN by default.
             assert a != approx(x)
 
             # If ``nan_ok=True``, then NaN is equal to NaN.
             assert op(a, approx(x, nan_ok=True))
 
     def test_int(self):
-        within_1e6 = [
-            (1000001, 1000000),
-            (-1000001, -1000000),
-        ]
+        within_1e6 = [(1000001, 1000000), (-1000001, -1000000)]
         for a, x in within_1e6:
             assert a == approx(x, rel=5e-6, abs=0)
             assert a != approx(x, rel=5e-7, abs=0)
             assert approx(x, rel=5e-6, abs=0) == a
             assert approx(x, rel=5e-7, abs=0) != a
 
     def test_decimal(self):
         within_1e6 = [
-            (Decimal('1.000001'), Decimal('1.0')),
-            (Decimal('-1.000001'), Decimal('-1.0')),
+            (Decimal("1.000001"), Decimal("1.0")),
+            (Decimal("-1.000001"), Decimal("-1.0")),
         ]
         for a, x in within_1e6:
-            assert a == approx(x, rel=Decimal('5e-6'), abs=0)
-            assert a != approx(x, rel=Decimal('5e-7'), abs=0)
-            assert approx(x, rel=Decimal('5e-6'), abs=0) == a
-            assert approx(x, rel=Decimal('5e-7'), abs=0) != a
+            assert a == approx(x)
+            assert a == approx(x, rel=Decimal("5e-6"), abs=0)
+            assert a != approx(x, rel=Decimal("5e-7"), abs=0)
+            assert approx(x, rel=Decimal("5e-6"), abs=0) == a
+            assert approx(x, rel=Decimal("5e-7"), abs=0) != a
 
     def test_fraction(self):
         within_1e6 = [
             (1 + Fraction(1, 1000000), Fraction(1)),
             (-1 - Fraction(-1, 1000000), Fraction(-1)),
         ]
         for a, x in within_1e6:
             assert a == approx(x, rel=5e-6, abs=0)
@@ -302,34 +293,34 @@ class TestApprox(object):
         assert approx(expected, rel=5e-7, abs=0) == actual
         assert approx(expected, rel=5e-8, abs=0) != actual
 
     def test_tuple_wrong_len(self):
         assert (1, 2) != approx((1,))
         assert (1, 2) != approx((1, 2, 3))
 
     def test_dict(self):
-        actual = {'a': 1 + 1e-7, 'b': 2 + 1e-8}
+        actual = {"a": 1 + 1e-7, "b": 2 + 1e-8}
         # Dictionaries became ordered in python3.6, so switch up the order here
         # to make sure it doesn't matter.
-        expected = {'b': 2, 'a': 1}
+        expected = {"b": 2, "a": 1}
 
         # Return false if any element is outside the tolerance.
         assert actual == approx(expected, rel=5e-7, abs=0)
         assert actual != approx(expected, rel=5e-8, abs=0)
         assert approx(expected, rel=5e-7, abs=0) == actual
         assert approx(expected, rel=5e-8, abs=0) != actual
 
     def test_dict_wrong_len(self):
-        assert {'a': 1, 'b': 2} != approx({'a': 1})
-        assert {'a': 1, 'b': 2} != approx({'a': 1, 'c': 2})
-        assert {'a': 1, 'b': 2} != approx({'a': 1, 'b': 2, 'c': 3})
+        assert {"a": 1, "b": 2} != approx({"a": 1})
+        assert {"a": 1, "b": 2} != approx({"a": 1, "c": 2})
+        assert {"a": 1, "b": 2} != approx({"a": 1, "b": 2, "c": 3})
 
     def test_numpy_array(self):
-        np = pytest.importorskip('numpy')
+        np = pytest.importorskip("numpy")
 
         actual = np.array([1 + 1e-7, 2 + 1e-8])
         expected = np.array([1, 2])
 
         # Return false if any element is outside the tolerance.
         assert actual == approx(expected, rel=5e-7, abs=0)
         assert actual != approx(expected, rel=5e-8, abs=0)
         assert approx(expected, rel=5e-7, abs=0) == expected
@@ -337,56 +328,79 @@ class TestApprox(object):
 
         # Should be able to compare lists with numpy arrays.
         assert list(actual) == approx(expected, rel=5e-7, abs=0)
         assert list(actual) != approx(expected, rel=5e-8, abs=0)
         assert actual == approx(list(expected), rel=5e-7, abs=0)
         assert actual != approx(list(expected), rel=5e-8, abs=0)
 
     def test_numpy_array_wrong_shape(self):
-        np = pytest.importorskip('numpy')
+        np = pytest.importorskip("numpy")
 
         a12 = np.array([[1, 2]])
         a21 = np.array([[1], [2]])
 
         assert a12 != approx(a21)
         assert a21 != approx(a12)
 
     def test_doctests(self):
         parser = doctest.DocTestParser()
         test = parser.get_doctest(
-            approx.__doc__,
-            {'approx': approx},
-            approx.__name__,
-            None, None,
+            approx.__doc__, {"approx": approx}, approx.__name__, None, None
         )
         runner = MyDocTestRunner()
         runner.run(test)
 
     def test_unicode_plus_minus(self, testdir):
         """
         Comparing approx instances inside lists should not produce an error in the detailed diff.
         Integration test for issue #2111.
         """
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def test_foo():
                 assert [3] == [pytest.approx(4)]
-        """)
-        expected = '4.0e-06'
+        """
+        )
+        expected = "4.0e-06"
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            '*At index 0 diff: 3 != 4 * {0}'.format(expected),
-            '=* 1 failed in *=',
-        ])
+        result.stdout.fnmatch_lines(
+            ["*At index 0 diff: 3 != 4 * {}".format(expected), "=* 1 failed in *="]
+        )
 
-    @pytest.mark.parametrize('op', [
-        pytest.param(operator.le, id='<='),
-        pytest.param(operator.lt, id='<'),
-        pytest.param(operator.ge, id='>='),
-        pytest.param(operator.gt, id='>'),
-    ])
+    @pytest.mark.parametrize(
+        "op",
+        [
+            pytest.param(operator.le, id="<="),
+            pytest.param(operator.lt, id="<"),
+            pytest.param(operator.ge, id=">="),
+            pytest.param(operator.gt, id=">"),
+        ],
+    )
     def test_comparison_operator_type_error(self, op):
         """
         pytest.approx should raise TypeError for operators other than == and != (#2003).
         """
         with pytest.raises(TypeError):
             op(1, approx(1, rel=1e-6, abs=1e-12))
+
+    def test_numpy_array_with_scalar(self):
+        np = pytest.importorskip("numpy")
+
+        actual = np.array([1 + 1e-7, 1 - 1e-8])
+        expected = 1.0
+
+        assert actual == approx(expected, rel=5e-7, abs=0)
+        assert actual != approx(expected, rel=5e-8, abs=0)
+        assert approx(expected, rel=5e-7, abs=0) == actual
+        assert approx(expected, rel=5e-8, abs=0) != actual
+
+    def test_numpy_scalar_with_array(self):
+        np = pytest.importorskip("numpy")
+
+        actual = 1.0
+        expected = np.array([1 + 1e-7, 1 - 1e-8])
+
+        assert actual == approx(expected, rel=5e-7, abs=0)
+        assert actual != approx(expected, rel=5e-8, abs=0)
+        assert approx(expected, rel=5e-7, abs=0) == actual
+        assert approx(expected, rel=5e-8, abs=0) != actual
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/python/collect.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/python/collect.py
@@ -1,326 +1,364 @@
 # -*- coding: utf-8 -*-
 import os
 import sys
 from textwrap import dedent
 
 import _pytest._code
-import py
 import pytest
-from _pytest.main import (
-    Collector,
-    EXIT_NOTESTSCOLLECTED
+from _pytest.main import EXIT_NOTESTSCOLLECTED
+from _pytest.nodes import Collector
+
+ignore_parametrized_marks = pytest.mark.filterwarnings(
+    "ignore:Applying marks directly to parameters"
 )
 
 
-ignore_parametrized_marks = pytest.mark.filterwarnings('ignore:Applying marks directly to parameters')
+class TestModule(object):
 
-
-class TestModule(object):
     def test_failing_import(self, testdir):
         modcol = testdir.getmodulecol("import alksdjalskdjalkjals")
         pytest.raises(Collector.CollectError, modcol.collect)
 
     def test_import_duplicate(self, testdir):
         a = testdir.mkdir("a")
         b = testdir.mkdir("b")
         p = a.ensure("test_whatever.py")
         p.pyimport()
-        del py.std.sys.modules['test_whatever']
+        del sys.modules["test_whatever"]
         b.ensure("test_whatever.py")
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*import*mismatch*",
-            "*imported*test_whatever*",
-            "*%s*" % a.join("test_whatever.py"),
-            "*not the same*",
-            "*%s*" % b.join("test_whatever.py"),
-            "*HINT*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*import*mismatch*",
+                "*imported*test_whatever*",
+                "*%s*" % a.join("test_whatever.py"),
+                "*not the same*",
+                "*%s*" % b.join("test_whatever.py"),
+                "*HINT*",
+            ]
+        )
 
     def test_import_prepend_append(self, testdir, monkeypatch):
         syspath = list(sys.path)
         monkeypatch.setattr(sys, "path", syspath)
         root1 = testdir.mkdir("root1")
         root2 = testdir.mkdir("root2")
         root1.ensure("x456.py")
         root2.ensure("x456.py")
         p = root2.join("test_x456.py")
         monkeypatch.syspath_prepend(str(root1))
-        p.write(dedent("""\
+        p.write(
+            dedent(
+                """\
             import x456
             def test():
                 assert x456.__file__.startswith(%r)
-        """ % str(root2)))
+        """
+                % str(root2)
+            )
+        )
         with root2.as_cwd():
             reprec = testdir.inline_run("--import-mode=append")
             reprec.assertoutcome(passed=0, failed=1)
             reprec = testdir.inline_run()
             reprec.assertoutcome(passed=1)
 
     def test_syntax_error_in_module(self, testdir):
         modcol = testdir.getmodulecol("this is a syntax error")
         pytest.raises(modcol.CollectError, modcol.collect)
         pytest.raises(modcol.CollectError, modcol.collect)
 
     def test_module_considers_pluginmanager_at_import(self, testdir):
         modcol = testdir.getmodulecol("pytest_plugins='xasdlkj',")
         pytest.raises(ImportError, lambda: modcol.obj)
 
     def test_invalid_test_module_name(self, testdir):
-        a = testdir.mkdir('a')
-        a.ensure('test_one.part1.py')
+        a = testdir.mkdir("a")
+        a.ensure("test_one.part1.py")
         result = testdir.runpytest("-rw")
-        result.stdout.fnmatch_lines([
-            "ImportError while importing test module*test_one.part1*",
-            "Hint: make sure your test modules/packages have valid Python names.",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "ImportError while importing test module*test_one.part1*",
+                "Hint: make sure your test modules/packages have valid Python names.",
+            ]
+        )
 
-    @pytest.mark.parametrize('verbose', [0, 1, 2])
+    @pytest.mark.parametrize("verbose", [0, 1, 2])
     def test_show_traceback_import_error(self, testdir, verbose):
         """Import errors when collecting modules should display the traceback (#1976).
 
         With low verbosity we omit pytest and internal modules, otherwise show all traceback entries.
         """
         testdir.makepyfile(
             foo_traceback_import_error="""
                from bar_traceback_import_error import NOT_AVAILABLE
            """,
             bar_traceback_import_error="",
         )
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
                import foo_traceback_import_error
-        """)
-        args = ('-v',) * verbose
+        """
+        )
+        args = ("-v",) * verbose
         result = testdir.runpytest(*args)
-        result.stdout.fnmatch_lines([
-            "ImportError while importing test module*",
-            "Traceback:",
-            "*from bar_traceback_import_error import NOT_AVAILABLE",
-            "*cannot import name *NOT_AVAILABLE*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "ImportError while importing test module*",
+                "Traceback:",
+                "*from bar_traceback_import_error import NOT_AVAILABLE",
+                "*cannot import name *NOT_AVAILABLE*",
+            ]
+        )
         assert result.ret == 2
 
         stdout = result.stdout.str()
-        for name in ('_pytest', os.path.join('py', '_path')):
+        for name in ("_pytest", os.path.join("py", "_path")):
             if verbose == 2:
                 assert name in stdout
             else:
                 assert name not in stdout
 
     def test_show_traceback_import_error_unicode(self, testdir):
         """Check test modules collected which raise ImportError with unicode messages
         are handled properly (#2336).
         """
-        testdir.makepyfile(u"""
+        testdir.makepyfile(
+            u"""
             # -*- coding: utf-8 -*-
             raise ImportError(u'Something bad happened ☺')
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "ImportError while importing test module*",
-            "Traceback:",
-            "*raise ImportError*Something bad happened*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "ImportError while importing test module*",
+                "Traceback:",
+                "*raise ImportError*Something bad happened*",
+            ]
+        )
         assert result.ret == 2
 
 
 class TestClass(object):
+
     def test_class_with_init_warning(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             class TestClass1(object):
                 def __init__(self):
                     pass
-        """)
+        """
+        )
         result = testdir.runpytest("-rw")
-        result.stdout.fnmatch_lines([
-            "*cannot collect test class 'TestClass1' because it has a __init__ constructor",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*cannot collect test class 'TestClass1' because it has a __init__ constructor"
+            ]
+        )
 
     def test_class_subclassobject(self, testdir):
-        testdir.getmodulecol("""
+        testdir.getmodulecol(
+            """
             class test(object):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*collected 0*",
-        ])
+        result.stdout.fnmatch_lines(["*collected 0*"])
 
     def test_static_method(self, testdir):
         """Support for collecting staticmethod tests (#2528, #2699)"""
-        testdir.getmodulecol("""
+        testdir.getmodulecol(
+            """
             import pytest
             class Test(object):
                 @staticmethod
                 def test_something():
                     pass
 
                 @pytest.fixture
                 def fix(self):
                     return 1
 
                 @staticmethod
                 def test_fix(fix):
                     assert fix == 1
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*collected 2 items*",
-            "*2 passed in*",
-        ])
+        result.stdout.fnmatch_lines(["*collected 2 items*", "*2 passed in*"])
 
     def test_setup_teardown_class_as_classmethod(self, testdir):
-        testdir.makepyfile(test_mod1="""
+        testdir.makepyfile(
+            test_mod1="""
             class TestClassMethod(object):
                 @classmethod
                 def setup_class(cls):
                     pass
                 def test_1(self):
                     pass
                 @classmethod
                 def teardown_class(cls):
                     pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*1 passed*",
-        ])
+        result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_issue1035_obj_has_getattr(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             class Chameleon(object):
                 def __getattr__(self, name):
                     return True
             chameleon = Chameleon()
-        """)
+        """
+        )
         colitems = modcol.collect()
         assert len(colitems) == 0
 
     def test_issue1579_namedtuple(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import collections
 
             TestCase = collections.namedtuple('TestCase', ['a'])
-        """)
-        result = testdir.runpytest('-rw')
+        """
+        )
+        result = testdir.runpytest("-rw")
         result.stdout.fnmatch_lines(
             "*cannot collect test class 'TestCase' "
             "because it has a __new__ constructor*"
         )
 
     def test_issue2234_property(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             class TestCase(object):
                 @property
                 def prop(self):
                     raise NotImplementedError()
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == EXIT_NOTESTSCOLLECTED
 
 
 class TestGenerator(object):
+
     def test_generative_functions(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             def func1(arg, arg2):
                 assert arg == arg2
 
             def test_gen():
                 yield func1, 17, 3*5
                 yield func1, 42, 6*7
-        """)
+        """
+        )
         colitems = modcol.collect()
         assert len(colitems) == 1
         gencol = colitems[0]
         assert isinstance(gencol, pytest.Generator)
         gencolitems = gencol.collect()
         assert len(gencolitems) == 2
         assert isinstance(gencolitems[0], pytest.Function)
         assert isinstance(gencolitems[1], pytest.Function)
-        assert gencolitems[0].name == '[0]'
-        assert gencolitems[0].obj.__name__ == 'func1'
+        assert gencolitems[0].name == "[0]"
+        assert gencolitems[0].obj.__name__ == "func1"
 
     def test_generative_methods(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             def func1(arg, arg2):
                 assert arg == arg2
             class TestGenMethods(object):
                 def test_gen(self):
                     yield func1, 17, 3*5
                     yield func1, 42, 6*7
-        """)
+        """
+        )
         gencol = modcol.collect()[0].collect()[0].collect()[0]
         assert isinstance(gencol, pytest.Generator)
         gencolitems = gencol.collect()
         assert len(gencolitems) == 2
         assert isinstance(gencolitems[0], pytest.Function)
         assert isinstance(gencolitems[1], pytest.Function)
-        assert gencolitems[0].name == '[0]'
-        assert gencolitems[0].obj.__name__ == 'func1'
+        assert gencolitems[0].name == "[0]"
+        assert gencolitems[0].obj.__name__ == "func1"
 
     def test_generative_functions_with_explicit_names(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             def func1(arg, arg2):
                 assert arg == arg2
 
             def test_gen():
                 yield "seventeen", func1, 17, 3*5
                 yield "fortytwo", func1, 42, 6*7
-        """)
+        """
+        )
         colitems = modcol.collect()
         assert len(colitems) == 1
         gencol = colitems[0]
         assert isinstance(gencol, pytest.Generator)
         gencolitems = gencol.collect()
         assert len(gencolitems) == 2
         assert isinstance(gencolitems[0], pytest.Function)
         assert isinstance(gencolitems[1], pytest.Function)
         assert gencolitems[0].name == "['seventeen']"
-        assert gencolitems[0].obj.__name__ == 'func1'
+        assert gencolitems[0].obj.__name__ == "func1"
         assert gencolitems[1].name == "['fortytwo']"
-        assert gencolitems[1].obj.__name__ == 'func1'
+        assert gencolitems[1].obj.__name__ == "func1"
 
     def test_generative_functions_unique_explicit_names(self, testdir):
         # generative
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             def func(): pass
             def test_gen():
                 yield "name", func
                 yield "name", func
-        """)
+        """
+        )
         colitems = modcol.collect()
         assert len(colitems) == 1
         gencol = colitems[0]
         assert isinstance(gencol, pytest.Generator)
         pytest.raises(ValueError, "gencol.collect()")
 
     def test_generative_methods_with_explicit_names(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             def func1(arg, arg2):
                 assert arg == arg2
             class TestGenMethods(object):
                 def test_gen(self):
                     yield "m1", func1, 17, 3*5
                     yield "m2", func1, 42, 6*7
-        """)
+        """
+        )
         gencol = modcol.collect()[0].collect()[0].collect()[0]
         assert isinstance(gencol, pytest.Generator)
         gencolitems = gencol.collect()
         assert len(gencolitems) == 2
         assert isinstance(gencolitems[0], pytest.Function)
         assert isinstance(gencolitems[1], pytest.Function)
         assert gencolitems[0].name == "['m1']"
-        assert gencolitems[0].obj.__name__ == 'func1'
+        assert gencolitems[0].obj.__name__ == "func1"
         assert gencolitems[1].name == "['m2']"
-        assert gencolitems[1].obj.__name__ == 'func1'
+        assert gencolitems[1].obj.__name__ == "func1"
 
     def test_order_of_execution_generator_same_codeline(self, testdir, tmpdir):
-        o = testdir.makepyfile("""
+        o = testdir.makepyfile(
+            """
             from __future__ import print_function
             def test_generative_order_of_execution():
                 import py, pytest
                 test_list = []
                 expected_list = list(range(6))
 
                 def list_append(item):
                     test_list.append(item)
@@ -328,24 +366,26 @@ class TestGenerator(object):
                 def assert_order_of_execution():
                     print('expected order', expected_list)
                     print('but got       ', test_list)
                     assert test_list == expected_list
 
                 for i in expected_list:
                     yield list_append, i
                 yield assert_order_of_execution
-        """)
+        """
+        )
         reprec = testdir.inline_run(o)
         passed, skipped, failed = reprec.countoutcomes()
         assert passed == 7
         assert not skipped and not failed
 
     def test_order_of_execution_generator_different_codeline(self, testdir):
-        o = testdir.makepyfile("""
+        o = testdir.makepyfile(
+            """
             from __future__ import print_function
             def test_generative_tests_different_codeline():
                 import py, pytest
                 test_list = []
                 expected_list = list(range(3))
 
                 def list_append_2():
                     test_list.append(2)
@@ -360,30 +400,32 @@ class TestGenerator(object):
                     print('expected order', expected_list)
                     print('but got       ', test_list)
                     assert test_list == expected_list
 
                 yield list_append_0
                 yield list_append_1
                 yield list_append_2
                 yield assert_order_of_execution
-        """)
+        """
+        )
         reprec = testdir.inline_run(o)
         passed, skipped, failed = reprec.countoutcomes()
         assert passed == 4
         assert not skipped and not failed
 
     def test_setupstate_is_preserved_134(self, testdir):
         # yield-based tests are messy wrt to setupstate because
         # during collection they already invoke setup functions
         # and then again when they are run.  For now, we want to make sure
         # that the old 1.3.4 behaviour is preserved such that all
         # yielded functions all share the same "self" instance that
         # has been used during collection.
-        o = testdir.makepyfile("""
+        o = testdir.makepyfile(
+            """
             setuplist = []
             class TestClass(object):
                 def setup_method(self, func):
                     #print "setup_method", self, func
                     setuplist.append(self)
                     self.init = 42
 
                 def teardown_method(self, func):
@@ -402,114 +444,128 @@ class TestGenerator(object):
             def test_setuplist():
                 # once for test_func2 during collection
                 # once for test_func1 during test run
                 # once for test_func2 during test run
                 #print setuplist
                 assert len(setuplist) == 3, len(setuplist)
                 assert setuplist[0] == setuplist[2], setuplist
                 assert setuplist[1] != setuplist[2], setuplist
-        """)
-        reprec = testdir.inline_run(o, '-v')
+        """
+        )
+        reprec = testdir.inline_run(o, "-v")
         passed, skipped, failed = reprec.countoutcomes()
         assert passed == 4
         assert not skipped and not failed
 
 
 class TestFunction(object):
+
     def test_getmodulecollector(self, testdir):
         item = testdir.getitem("def test_func(): pass")
         modcol = item.getparent(pytest.Module)
         assert isinstance(modcol, pytest.Module)
-        assert hasattr(modcol.obj, 'test_func')
+        assert hasattr(modcol.obj, "test_func")
 
     def test_function_as_object_instance_ignored(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             class A(object):
                 def __call__(self, tmpdir):
                     0/0
 
             test_a = A()
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome()
 
     def test_function_equality(self, testdir, tmpdir):
         from _pytest.fixtures import FixtureManager
+
         config = testdir.parseconfigure()
         session = testdir.Session(config)
         session._fixturemanager = FixtureManager(session)
 
         def func1():
             pass
 
         def func2():
             pass
 
-        f1 = pytest.Function(name="name", parent=session, config=config,
-                             args=(1,), callobj=func1)
+        f1 = pytest.Function(
+            name="name", parent=session, config=config, args=(1,), callobj=func1
+        )
         assert f1 == f1
-        f2 = pytest.Function(name="name", config=config,
-                             callobj=func2, parent=session)
+        f2 = pytest.Function(name="name", config=config, callobj=func2, parent=session)
         assert f1 != f2
 
     def test_issue197_parametrize_emptyset(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.parametrize('arg', [])
             def test_function(arg):
                 pass
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(skipped=1)
 
     def test_single_tuple_unwraps_values(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.parametrize(('arg',), [(1,)])
             def test_function(arg):
                 assert arg == 1
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_issue213_parametrize_value_no_equal(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             class A(object):
                 def __eq__(self, other):
                     raise ValueError("not possible")
             @pytest.mark.parametrize('arg', [A()])
             def test_function(arg):
                 assert arg.__class__.__name__ == "A"
-        """)
+        """
+        )
         reprec = testdir.inline_run("--fulltrace")
         reprec.assertoutcome(passed=1)
 
     def test_parametrize_with_non_hashable_values(self, testdir):
         """Test parametrization with non-hashable values."""
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             archival_mapping = {
                 '1.0': {'tag': '1.0'},
                 '1.2.2a1': {'tag': 'release-1.2.2a1'},
             }
 
             import pytest
             @pytest.mark.parametrize('key value'.split(),
                                      archival_mapping.items())
             def test_archival_to_version(key, value):
                 assert key in archival_mapping
                 assert value == archival_mapping[key]
-        """)
+        """
+        )
         rec = testdir.inline_run()
         rec.assertoutcome(passed=2)
 
     def test_parametrize_with_non_hashable_values_indirect(self, testdir):
         """Test parametrization with non-hashable values with indirect parametrization."""
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             archival_mapping = {
                 '1.0': {'tag': '1.0'},
                 '1.2.2a1': {'tag': 'release-1.2.2a1'},
             }
 
             import pytest
 
             @pytest.fixture
@@ -520,23 +576,25 @@ class TestFunction(object):
             def value(request):
                 return request.param
 
             @pytest.mark.parametrize('key value'.split(),
                                      archival_mapping.items(), indirect=True)
             def test_archival_to_version(key, value):
                 assert key in archival_mapping
                 assert value == archival_mapping[key]
-        """)
+        """
+        )
         rec = testdir.inline_run()
         rec.assertoutcome(passed=2)
 
     def test_parametrize_overrides_fixture(self, testdir):
         """Test parametrization when parameter overrides existing fixture with same name."""
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def value():
                 return 'value'
 
             @pytest.mark.parametrize('value',
                                      ['overridden'])
@@ -547,569 +605,645 @@ class TestFunction(object):
             def test_not_overridden(value, somevalue):
                 assert value == 'value'
                 assert somevalue == 'overridden'
 
             @pytest.mark.parametrize('other,value', [('foo', 'overridden')])
             def test_overridden_via_multiparam(other, value):
                 assert other == 'foo'
                 assert value == 'overridden'
-        """)
+        """
+        )
         rec = testdir.inline_run()
         rec.assertoutcome(passed=3)
 
     def test_parametrize_overrides_parametrized_fixture(self, testdir):
         """Test parametrization when parameter overrides existing parametrized fixture with same name."""
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(params=[1, 2])
             def value(request):
                 return request.param
 
             @pytest.mark.parametrize('value',
                                      ['overridden'])
             def test_overridden_via_param(value):
                 assert value == 'overridden'
-        """)
+        """
+        )
         rec = testdir.inline_run()
         rec.assertoutcome(passed=1)
 
     @ignore_parametrized_marks
     def test_parametrize_with_mark(self, testdir):
-        items = testdir.getitems("""
+        items = testdir.getitems(
+            """
             import pytest
             @pytest.mark.foo
             @pytest.mark.parametrize('arg', [
                 1,
                 pytest.mark.bar(pytest.mark.baz(2))
             ])
             def test_function(arg):
                 pass
-        """)
+        """
+        )
         keywords = [item.keywords for item in items]
-        assert 'foo' in keywords[0] and 'bar' not in keywords[0] and 'baz' not in keywords[0]
-        assert 'foo' in keywords[1] and 'bar' in keywords[1] and 'baz' in keywords[1]
+        assert (
+            "foo" in keywords[0]
+            and "bar" not in keywords[0]
+            and "baz" not in keywords[0]
+        )
+        assert "foo" in keywords[1] and "bar" in keywords[1] and "baz" in keywords[1]
 
     def test_function_equality_with_callspec(self, testdir, tmpdir):
-        items = testdir.getitems("""
+        items = testdir.getitems(
+            """
             import pytest
             @pytest.mark.parametrize('arg', [1,2])
             def test_function(arg):
                 pass
-        """)
+        """
+        )
         assert items[0] != items[1]
         assert not (items[0] == items[1])
 
     def test_pyfunc_call(self, testdir):
         item = testdir.getitem("def test_func(): raise ValueError")
         config = item.config
 
         class MyPlugin1(object):
+
             def pytest_pyfunc_call(self, pyfuncitem):
                 raise ValueError
 
         class MyPlugin2(object):
+
             def pytest_pyfunc_call(self, pyfuncitem):
                 return True
 
         config.pluginmanager.register(MyPlugin1())
         config.pluginmanager.register(MyPlugin2())
         config.hook.pytest_runtest_setup(item=item)
         config.hook.pytest_pyfunc_call(pyfuncitem=item)
 
     def test_multiple_parametrize(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             import pytest
             @pytest.mark.parametrize('x', [0, 1])
             @pytest.mark.parametrize('y', [2, 3])
             def test1(x, y):
                 pass
-        """)
+        """
+        )
         colitems = modcol.collect()
-        assert colitems[0].name == 'test1[2-0]'
-        assert colitems[1].name == 'test1[2-1]'
-        assert colitems[2].name == 'test1[3-0]'
-        assert colitems[3].name == 'test1[3-1]'
+        assert colitems[0].name == "test1[2-0]"
+        assert colitems[1].name == "test1[2-1]"
+        assert colitems[2].name == "test1[3-0]"
+        assert colitems[3].name == "test1[3-1]"
 
     def test_issue751_multiple_parametrize_with_ids(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             import pytest
             @pytest.mark.parametrize('x', [0], ids=['c'])
             @pytest.mark.parametrize('y', [0, 1], ids=['a', 'b'])
             class Test(object):
                 def test1(self, x, y):
                     pass
                 def test2(self, x, y):
                     pass
-        """)
+        """
+        )
         colitems = modcol.collect()[0].collect()[0].collect()
-        assert colitems[0].name == 'test1[a-c]'
-        assert colitems[1].name == 'test1[b-c]'
-        assert colitems[2].name == 'test2[a-c]'
-        assert colitems[3].name == 'test2[b-c]'
+        assert colitems[0].name == "test1[a-c]"
+        assert colitems[1].name == "test1[b-c]"
+        assert colitems[2].name == "test2[a-c]"
+        assert colitems[3].name == "test2[b-c]"
 
     @ignore_parametrized_marks
     def test_parametrize_skipif(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             m = pytest.mark.skipif('True')
 
             @pytest.mark.parametrize('x', [0, 1, m(2)])
             def test_skip_if(x):
                 assert x < 2
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines('* 2 passed, 1 skipped in *')
+        result.stdout.fnmatch_lines("* 2 passed, 1 skipped in *")
 
     @ignore_parametrized_marks
     def test_parametrize_skip(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             m = pytest.mark.skip('')
 
             @pytest.mark.parametrize('x', [0, 1, m(2)])
             def test_skip(x):
                 assert x < 2
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines('* 2 passed, 1 skipped in *')
+        result.stdout.fnmatch_lines("* 2 passed, 1 skipped in *")
 
     @ignore_parametrized_marks
     def test_parametrize_skipif_no_skip(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             m = pytest.mark.skipif('False')
 
             @pytest.mark.parametrize('x', [0, 1, m(2)])
             def test_skipif_no_skip(x):
                 assert x < 2
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines('* 1 failed, 2 passed in *')
+        result.stdout.fnmatch_lines("* 1 failed, 2 passed in *")
 
     @ignore_parametrized_marks
     def test_parametrize_xfail(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             m = pytest.mark.xfail('True')
 
             @pytest.mark.parametrize('x', [0, 1, m(2)])
             def test_xfail(x):
                 assert x < 2
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines('* 2 passed, 1 xfailed in *')
+        result.stdout.fnmatch_lines("* 2 passed, 1 xfailed in *")
 
     @ignore_parametrized_marks
     def test_parametrize_passed(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             m = pytest.mark.xfail('True')
 
             @pytest.mark.parametrize('x', [0, 1, m(2)])
             def test_xfail(x):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines('* 2 passed, 1 xpassed in *')
+        result.stdout.fnmatch_lines("* 2 passed, 1 xpassed in *")
 
     @ignore_parametrized_marks
     def test_parametrize_xfail_passed(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             m = pytest.mark.xfail('False')
 
             @pytest.mark.parametrize('x', [0, 1, m(2)])
             def test_passed(x):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines('* 3 passed in *')
+        result.stdout.fnmatch_lines("* 3 passed in *")
 
     def test_function_original_name(self, testdir):
-        items = testdir.getitems("""
+        items = testdir.getitems(
+            """
             import pytest
             @pytest.mark.parametrize('arg', [1,2])
             def test_func(arg):
                 pass
-        """)
-        assert [x.originalname for x in items] == ['test_func', 'test_func']
+        """
+        )
+        assert [x.originalname for x in items] == ["test_func", "test_func"]
 
 
 class TestSorting(object):
+
     def test_check_equality(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             def test_pass(): pass
             def test_fail(): assert 0
-        """)
+        """
+        )
         fn1 = testdir.collect_by_name(modcol, "test_pass")
         assert isinstance(fn1, pytest.Function)
         fn2 = testdir.collect_by_name(modcol, "test_pass")
         assert isinstance(fn2, pytest.Function)
 
         assert fn1 == fn2
         assert fn1 != modcol
-        if py.std.sys.version_info < (3, 0):
-            assert cmp(fn1, fn2) == 0
+        if sys.version_info < (3, 0):
+            assert cmp(fn1, fn2) == 0  # NOQA
         assert hash(fn1) == hash(fn2)
 
         fn3 = testdir.collect_by_name(modcol, "test_fail")
         assert isinstance(fn3, pytest.Function)
         assert not (fn1 == fn3)
         assert fn1 != fn3
 
         for fn in fn1, fn2, fn3:
             assert fn != 3
             assert fn != modcol
             assert fn != [1, 2, 3]
             assert [1, 2, 3] != fn
             assert modcol != fn
 
     def test_allow_sane_sorting_for_decorators(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             def dec(f):
                 g = lambda: f(2)
                 g.place_as = f
                 return g
 
 
             def test_b(y):
                 pass
             test_b = dec(test_b)
 
             def test_a(y):
                 pass
             test_a = dec(test_a)
-        """)
+        """
+        )
         colitems = modcol.collect()
         assert len(colitems) == 2
-        assert [item.name for item in colitems] == ['test_b', 'test_a']
+        assert [item.name for item in colitems] == ["test_b", "test_a"]
 
 
 class TestConftestCustomization(object):
+
     def test_pytest_pycollect_module(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             class MyModule(pytest.Module):
                 pass
             def pytest_pycollect_makemodule(path, parent):
                 if path.basename == "test_xyz.py":
                     return MyModule(path, parent)
-        """)
+        """
+        )
         testdir.makepyfile("def test_some(): pass")
         testdir.makepyfile(test_xyz="def test_func(): pass")
         result = testdir.runpytest("--collect-only")
-        result.stdout.fnmatch_lines([
-            "*<Module*test_pytest*",
-            "*<MyModule*xyz*",
-        ])
+        result.stdout.fnmatch_lines(["*<Module*test_pytest*", "*<MyModule*xyz*"])
 
     def test_customized_pymakemodule_issue205_subdir(self, testdir):
         b = testdir.mkdir("a").mkdir("b")
-        b.join("conftest.py").write(_pytest._code.Source("""
+        b.join("conftest.py").write(
+            _pytest._code.Source(
+                """
             import pytest
             @pytest.hookimpl(hookwrapper=True)
             def pytest_pycollect_makemodule():
                 outcome = yield
                 mod = outcome.get_result()
                 mod.obj.hello = "world"
-        """))
-        b.join("test_module.py").write(_pytest._code.Source("""
+        """
+            )
+        )
+        b.join("test_module.py").write(
+            _pytest._code.Source(
+                """
             def test_hello():
                 assert hello == "world"
-        """))
+        """
+            )
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_customized_pymakeitem(self, testdir):
         b = testdir.mkdir("a").mkdir("b")
-        b.join("conftest.py").write(_pytest._code.Source("""
+        b.join("conftest.py").write(
+            _pytest._code.Source(
+                """
             import pytest
             @pytest.hookimpl(hookwrapper=True)
             def pytest_pycollect_makeitem():
                 outcome = yield
                 if outcome.excinfo is None:
                     result = outcome.get_result()
                     if result:
                         for func in result:
                             func._some123 = "world"
-        """))
-        b.join("test_module.py").write(_pytest._code.Source("""
+        """
+            )
+        )
+        b.join("test_module.py").write(
+            _pytest._code.Source(
+                """
             import pytest
 
             @pytest.fixture()
             def obj(request):
                 return request.node._some123
             def test_hello(obj):
                 assert obj == "world"
-        """))
+        """
+            )
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_pytest_pycollect_makeitem(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             class MyFunction(pytest.Function):
                 pass
             def pytest_pycollect_makeitem(collector, name, obj):
                 if name == "some":
                     return MyFunction(name, collector)
-        """)
+        """
+        )
         testdir.makepyfile("def some(): pass")
         result = testdir.runpytest("--collect-only")
-        result.stdout.fnmatch_lines([
-            "*MyFunction*some*",
-        ])
+        result.stdout.fnmatch_lines(["*MyFunction*some*"])
 
     def test_makeitem_non_underscore(self, testdir, monkeypatch):
         modcol = testdir.getmodulecol("def _hello(): pass")
         values = []
-        monkeypatch.setattr(pytest.Module, 'makeitem',
-                            lambda self, name, obj: values.append(name))
+        monkeypatch.setattr(
+            pytest.Module, "makeitem", lambda self, name, obj: values.append(name)
+        )
         values = modcol.collect()
-        assert '_hello' not in values
+        assert "_hello" not in values
 
     def test_issue2369_collect_module_fileext(self, testdir):
         """Ensure we can collect files with weird file extensions as Python
         modules (#2369)"""
         # We'll implement a little finder and loader to import files containing
         # Python source code whose file extension is ".narf".
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import sys, os, imp
             from _pytest.python import Module
 
-            class Loader:
+            class Loader(object):
                 def load_module(self, name):
                     return imp.load_source(name, name + ".narf")
-            class Finder:
+            class Finder(object):
                 def find_module(self, name, path=None):
                     if os.path.exists(name + ".narf"):
                         return Loader()
             sys.meta_path.append(Finder())
 
             def pytest_collect_file(path, parent):
                 if path.ext == ".narf":
-                    return Module(path, parent)""")
-        testdir.makefile(".narf", """
+                    return Module(path, parent)"""
+        )
+        testdir.makefile(
+            ".narf",
+            """
             def test_something():
-                assert 1 + 1 == 2""")
+                assert 1 + 1 == 2""",
+        )
         # Use runpytest_subprocess, since we're futzing with sys.meta_path.
         result = testdir.runpytest_subprocess()
-        result.stdout.fnmatch_lines('*1 passed*')
+        result.stdout.fnmatch_lines("*1 passed*")
 
 
 def test_setup_only_available_in_subdir(testdir):
     sub1 = testdir.mkpydir("sub1")
     sub2 = testdir.mkpydir("sub2")
-    sub1.join("conftest.py").write(_pytest._code.Source("""
+    sub1.join("conftest.py").write(
+        _pytest._code.Source(
+            """
         import pytest
         def pytest_runtest_setup(item):
             assert item.fspath.purebasename == "test_in_sub1"
         def pytest_runtest_call(item):
             assert item.fspath.purebasename == "test_in_sub1"
         def pytest_runtest_teardown(item):
             assert item.fspath.purebasename == "test_in_sub1"
-    """))
-    sub2.join("conftest.py").write(_pytest._code.Source("""
+    """
+        )
+    )
+    sub2.join("conftest.py").write(
+        _pytest._code.Source(
+            """
         import pytest
         def pytest_runtest_setup(item):
             assert item.fspath.purebasename == "test_in_sub2"
         def pytest_runtest_call(item):
             assert item.fspath.purebasename == "test_in_sub2"
         def pytest_runtest_teardown(item):
             assert item.fspath.purebasename == "test_in_sub2"
-    """))
+    """
+        )
+    )
     sub1.join("test_in_sub1.py").write("def test_1(): pass")
     sub2.join("test_in_sub2.py").write("def test_2(): pass")
     result = testdir.runpytest("-v", "-s")
     result.assert_outcomes(passed=2)
 
 
 def test_modulecol_roundtrip(testdir):
     modcol = testdir.getmodulecol("pass", withinit=True)
     trail = modcol.nodeid
     newcol = modcol.session.perform_collect([trail], genitems=0)[0]
     assert modcol.name == newcol.name
 
 
 class TestTracebackCutting(object):
+
     def test_skip_simple(self):
         excinfo = pytest.raises(pytest.skip.Exception, 'pytest.skip("xxx")')
         assert excinfo.traceback[-1].frame.code.name == "skip"
         assert excinfo.traceback[-1].ishidden()
 
     def test_traceback_argsetup(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture
             def hello(request):
                 raise ValueError("xyz")
-        """)
+        """
+        )
         p = testdir.makepyfile("def test(hello): pass")
         result = testdir.runpytest(p)
         assert result.ret != 0
         out = result.stdout.str()
         assert "xyz" in out
         assert "conftest.py:5: ValueError" in out
         numentries = out.count("_ _ _")  # separator for traceback entries
         assert numentries == 0
 
         result = testdir.runpytest("--fulltrace", p)
         out = result.stdout.str()
         assert "conftest.py:5: ValueError" in out
         numentries = out.count("_ _ _ _")  # separator for traceback entries
         assert numentries > 3
 
     def test_traceback_error_during_import(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             x = 1
             x = 2
             x = 17
             asd
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret != 0
         out = result.stdout.str()
         assert "x = 1" not in out
         assert "x = 2" not in out
-        result.stdout.fnmatch_lines([
-            " *asd*",
-            "E*NameError*",
-        ])
+        result.stdout.fnmatch_lines([" *asd*", "E*NameError*"])
         result = testdir.runpytest("--fulltrace")
         out = result.stdout.str()
         assert "x = 1" in out
         assert "x = 2" in out
-        result.stdout.fnmatch_lines([
-            ">*asd*",
-            "E*NameError*",
-        ])
+        result.stdout.fnmatch_lines([">*asd*", "E*NameError*"])
 
     def test_traceback_filter_error_during_fixture_collection(self, testdir):
         """integration test for issue #995.
         """
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             def fail_me(func):
                 ns = {}
                 exec('def w(): raise ValueError("fail me")', ns)
                 return ns['w']
 
             @pytest.fixture(scope='class')
             @fail_me
             def fail_fixture():
                 pass
 
             def test_failing_fixture(fail_fixture):
                pass
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret != 0
         out = result.stdout.str()
         assert "INTERNALERROR>" not in out
-        result.stdout.fnmatch_lines([
-            "*ValueError: fail me*",
-            "* 1 error in *",
-        ])
+        result.stdout.fnmatch_lines(["*ValueError: fail me*", "* 1 error in *"])
 
     def test_filter_traceback_generated_code(self):
         """test that filter_traceback() works with the fact that
         py.code.Code.path attribute might return an str object.
         In this case, one of the entries on the traceback was produced by
         dynamically generated code.
         See: https://bitbucket.org/pytest-dev/py/issues/71
         This fixes #995.
         """
         from _pytest.python import filter_traceback
+
         try:
             ns = {}
-            exec('def foo(): raise ValueError', ns)
-            ns['foo']()
+            exec("def foo(): raise ValueError", ns)
+            ns["foo"]()
         except ValueError:
             _, _, tb = sys.exc_info()
 
         tb = _pytest._code.Traceback(tb)
         assert isinstance(tb[-1].path, str)
         assert not filter_traceback(tb[-1])
 
     def test_filter_traceback_path_no_longer_valid(self, testdir):
         """test that filter_traceback() works with the fact that
         py.code.Code.path attribute might return an str object.
         In this case, one of the files in the traceback no longer exists.
         This fixes #1133.
         """
         from _pytest.python import filter_traceback
+
         testdir.syspathinsert()
-        testdir.makepyfile(filter_traceback_entry_as_str='''
+        testdir.makepyfile(
+            filter_traceback_entry_as_str="""
             def foo():
                 raise ValueError
-        ''')
+        """
+        )
         try:
             import filter_traceback_entry_as_str
+
             filter_traceback_entry_as_str.foo()
         except ValueError:
             _, _, tb = sys.exc_info()
 
-        testdir.tmpdir.join('filter_traceback_entry_as_str.py').remove()
+        testdir.tmpdir.join("filter_traceback_entry_as_str.py").remove()
         tb = _pytest._code.Traceback(tb)
         assert isinstance(tb[-1].path, str)
         assert filter_traceback(tb[-1])
 
 
 class TestReportInfo(object):
+
     def test_itemreport_reportinfo(self, testdir, linecomp):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             class MyFunction(pytest.Function):
                 def reportinfo(self):
                     return "ABCDE", 42, "custom"
             def pytest_pycollect_makeitem(collector, name, obj):
                 if name == "test_func":
                     return MyFunction(name, parent=collector)
-        """)
+        """
+        )
         item = testdir.getitem("def test_func(): pass")
         item.config.pluginmanager.getplugin("runner")
         assert item.location == ("ABCDE", 42, "custom")
 
     def test_func_reportinfo(self, testdir):
         item = testdir.getitem("def test_func(): pass")
         fspath, lineno, modpath = item.reportinfo()
         assert fspath == item.fspath
         assert lineno == 0
         assert modpath == "test_func"
 
     def test_class_reportinfo(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             # lineno 0
             class TestClass(object):
                 def test_hello(self): pass
-        """)
+        """
+        )
         classcol = testdir.collect_by_name(modcol, "TestClass")
         fspath, lineno, msg = classcol.reportinfo()
         assert fspath == modcol.fspath
         assert lineno == 1
         assert msg == "TestClass"
 
     def test_generator_reportinfo(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             # lineno 0
             def test_gen():
                 def check(x):
                     assert x
                 yield check, 3
-        """)
+        """
+        )
         gencol = testdir.collect_by_name(modcol, "test_gen")
         fspath, lineno, modpath = gencol.reportinfo()
         assert fspath == modcol.fspath
         assert lineno == 1
         assert modpath == "test_gen"
 
         genitem = gencol.collect()[0]
         fspath, lineno, modpath = genitem.reportinfo()
@@ -1125,151 +1259,159 @@ class TestReportInfo(object):
                 yield check, 3
             class TestClass(object):
                 def test_method(self):
                     pass
        """
 
     def test_reportinfo_with_nasty_getattr(self, testdir):
         # https://github.com/pytest-dev/pytest/issues/1204
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             # lineno 0
             class TestClass(object):
                 def __getattr__(self, name):
                     return "this is not an int"
 
                 def test_foo(self):
                     pass
-        """)
+        """
+        )
         classcol = testdir.collect_by_name(modcol, "TestClass")
         instance = classcol.collect()[0]
         fspath, lineno, msg = instance.reportinfo()
 
 
 def test_customized_python_discovery(testdir):
-    testdir.makeini("""
+    testdir.makeini(
+        """
         [pytest]
         python_files=check_*.py
         python_classes=Check
         python_functions=check
-    """)
-    p = testdir.makepyfile("""
+    """
+    )
+    p = testdir.makepyfile(
+        """
         def check_simple():
             pass
         class CheckMyApp(object):
             def check_meth(self):
                 pass
-    """)
+    """
+    )
     p2 = p.new(basename=p.basename.replace("test", "check"))
     p.move(p2)
     result = testdir.runpytest("--collect-only", "-s")
-    result.stdout.fnmatch_lines([
-        "*check_customized*",
-        "*check_simple*",
-        "*CheckMyApp*",
-        "*check_meth*",
-    ])
+    result.stdout.fnmatch_lines(
+        ["*check_customized*", "*check_simple*", "*CheckMyApp*", "*check_meth*"]
+    )
 
     result = testdir.runpytest()
     assert result.ret == 0
-    result.stdout.fnmatch_lines([
-        "*2 passed*",
-    ])
+    result.stdout.fnmatch_lines(["*2 passed*"])
 
 
 def test_customized_python_discovery_functions(testdir):
-    testdir.makeini("""
+    testdir.makeini(
+        """
         [pytest]
         python_functions=_test
-    """)
-    testdir.makepyfile("""
+    """
+    )
+    testdir.makepyfile(
+        """
         def _test_underscore():
             pass
-    """)
+    """
+    )
     result = testdir.runpytest("--collect-only", "-s")
-    result.stdout.fnmatch_lines([
-        "*_test_underscore*",
-    ])
+    result.stdout.fnmatch_lines(["*_test_underscore*"])
 
     result = testdir.runpytest()
     assert result.ret == 0
-    result.stdout.fnmatch_lines([
-        "*1 passed*",
-    ])
+    result.stdout.fnmatch_lines(["*1 passed*"])
 
 
 def test_collector_attributes(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         import pytest
         def pytest_pycollect_makeitem(collector):
             assert collector.Function == pytest.Function
             assert collector.Class == pytest.Class
             assert collector.Instance == pytest.Instance
             assert collector.Module == pytest.Module
-    """)
-    testdir.makepyfile("""
+    """
+    )
+    testdir.makepyfile(
+        """
          def test_hello():
             pass
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        "*1 passed*",
-    ])
+    result.stdout.fnmatch_lines(["*1 passed*"])
 
 
 def test_customize_through_attributes(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         import pytest
         class MyFunction(pytest.Function):
             pass
         class MyInstance(pytest.Instance):
             Function = MyFunction
         class MyClass(pytest.Class):
             Instance = MyInstance
 
         def pytest_pycollect_makeitem(collector, name, obj):
             if name.startswith("MyTestClass"):
                 return MyClass(name, parent=collector)
-    """)
-    testdir.makepyfile("""
+    """
+    )
+    testdir.makepyfile(
+        """
          class MyTestClass(object):
             def test_hello(self):
                 pass
-    """)
+    """
+    )
     result = testdir.runpytest("--collect-only")
-    result.stdout.fnmatch_lines([
-        "*MyClass*",
-        "*MyInstance*",
-        "*MyFunction*test_hello*",
-    ])
+    result.stdout.fnmatch_lines(
+        ["*MyClass*", "*MyInstance*", "*MyFunction*test_hello*"]
+    )
 
 
 def test_unorderable_types(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         class TestJoinEmpty(object):
             pass
 
         def make_test():
             class Test(object):
                 pass
             Test.__name__ = "TestFoo"
             return Test
         TestFoo = make_test()
-    """)
+    """
+    )
     result = testdir.runpytest()
     assert "TypeError" not in result.stdout.str()
     assert result.ret == EXIT_NOTESTSCOLLECTED
 
 
 def test_collect_functools_partial(testdir):
     """
     Test that collection of functools.partial object works, and arguments
     to the wrapped functions are dealt correctly (see #811).
     """
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import functools
         import pytest
 
         @pytest.fixture
         def fix1():
             return 'fix1'
 
         @pytest.fixture
@@ -1293,110 +1435,121 @@ def test_collect_functools_partial(testd
         test_ok_2 = functools.partial(check1, i=2, fix1='fix1')
         test_ok_3 = functools.partial(check1, 2)
         test_ok_4 = functools.partial(check2, i=2)
         test_ok_5 = functools.partial(check3, i=2)
         test_ok_6 = functools.partial(check3, i=2, fix1='fix1')
 
         test_fail_1 = functools.partial(check2, 2)
         test_fail_2 = functools.partial(check3, 2)
-    """)
+    """
+    )
     result = testdir.inline_run()
     result.assertoutcome(passed=6, failed=2)
 
 
 def test_dont_collect_non_function_callable(testdir):
     """Test for issue https://github.com/pytest-dev/pytest/issues/331
 
     In this case an INTERNALERROR occurred trying to report the failure of
     a test like this one because py test failed to get the source lines.
     """
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         class Oh(object):
             def __call__(self):
                 pass
 
         test_a = Oh()
 
         def test_real():
             pass
-    """)
-    result = testdir.runpytest('-rw')
-    result.stdout.fnmatch_lines([
-        '*collected 1 item*',
-        "*cannot collect 'test_a' because it is not a function*",
-        '*1 passed, 1 warnings in *',
-    ])
+    """
+    )
+    result = testdir.runpytest("-rw")
+    result.stdout.fnmatch_lines(
+        [
+            "*collected 1 item*",
+            "*cannot collect 'test_a' because it is not a function*",
+            "*1 passed, 1 warnings in *",
+        ]
+    )
 
 
 def test_class_injection_does_not_break_collection(testdir):
     """Tests whether injection during collection time will terminate testing.
 
     In this case the error should not occur if the TestClass itself
     is modified during collection time, and the original method list
     is still used for collection.
     """
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         from test_inject import TestClass
         def pytest_generate_tests(metafunc):
             TestClass.changed_var = {}
-    """)
-    testdir.makepyfile(test_inject='''
+    """
+    )
+    testdir.makepyfile(
+        test_inject='''
          class TestClass(object):
             def test_injection(self):
                 """Test being parametrized."""
                 pass
-    ''')
+    '''
+    )
     result = testdir.runpytest()
     assert "RuntimeError: dictionary changed size during iteration" not in result.stdout.str()
-    result.stdout.fnmatch_lines(['*1 passed*'])
+    result.stdout.fnmatch_lines(["*1 passed*"])
 
 
 def test_syntax_error_with_non_ascii_chars(testdir):
     """Fix decoding issue while formatting SyntaxErrors during collection (#578)
     """
-    testdir.makepyfile(u"""
+    testdir.makepyfile(
+        u"""
     # -*- coding: UTF-8 -*-
 

-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        '*ERROR collecting*',
-        '*SyntaxError*',
-        '*1 error in*',
-    ])
+    result.stdout.fnmatch_lines(["*ERROR collecting*", "*SyntaxError*", "*1 error in*"])
 
 
 def test_skip_duplicates_by_default(testdir):
     """Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)
 
     Ignore duplicate directories.
     """
     a = testdir.mkdir("a")
     fh = a.join("test_a.py")
-    fh.write(_pytest._code.Source("""
+    fh.write(
+        _pytest._code.Source(
+            """
         import pytest
         def test_real():
             pass
-    """))
+    """
+        )
+    )
     result = testdir.runpytest(a.strpath, a.strpath)
-    result.stdout.fnmatch_lines([
-        '*collected 1 item*',
-    ])
+    result.stdout.fnmatch_lines(["*collected 1 item*"])
 
 
 def test_keep_duplicates(testdir):
     """Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)
 
     Use --keep-duplicates to collect tests from duplicate directories.
     """
     a = testdir.mkdir("a")
     fh = a.join("test_a.py")
-    fh.write(_pytest._code.Source("""
+    fh.write(
+        _pytest._code.Source(
+            """
         import pytest
         def test_real():
             pass
-    """))
+    """
+        )
+    )
     result = testdir.runpytest("--keep-duplicates", a.strpath, a.strpath)
-    result.stdout.fnmatch_lines([
-        '*collected 2 item*',
-    ])
+    result.stdout.fnmatch_lines(["*collected 2 item*"])
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/python/fixture.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/python/fixture.py
@@ -1,564 +1,714 @@
 from textwrap import dedent
 
 import _pytest._code
 import pytest
 from _pytest.pytester import get_public_names
-from _pytest.fixtures import FixtureLookupError
+from _pytest.fixtures import FixtureLookupError, FixtureRequest
 from _pytest import fixtures
 
 
 def test_getfuncargnames():
+
     def f():
         pass
+
     assert not fixtures.getfuncargnames(f)
 
     def g(arg):
         pass
-    assert fixtures.getfuncargnames(g) == ('arg',)
+
+    assert fixtures.getfuncargnames(g) == ("arg",)
 
     def h(arg1, arg2="hello"):
         pass
-    assert fixtures.getfuncargnames(h) == ('arg1',)
+
+    assert fixtures.getfuncargnames(h) == ("arg1",)
 
     def h(arg1, arg2, arg3="hello"):
         pass
-    assert fixtures.getfuncargnames(h) == ('arg1', 'arg2')
+
+    assert fixtures.getfuncargnames(h) == ("arg1", "arg2")
 
     class A(object):
+
         def f(self, arg1, arg2="hello"):
             pass
 
         @staticmethod
         def static(arg1, arg2):
             pass
 
-    assert fixtures.getfuncargnames(A().f) == ('arg1',)
-    assert fixtures.getfuncargnames(A.static, cls=A) == ('arg1', 'arg2')
+    assert fixtures.getfuncargnames(A().f) == ("arg1",)
+    assert fixtures.getfuncargnames(A.static, cls=A) == ("arg1", "arg2")
 
 
 class TestFillFixtures(object):
+
     def test_fillfuncargs_exposed(self):
         # used by oejskit, kept for compatibility
         assert pytest._fillfuncargs == fixtures.fillfixtures
 
     def test_funcarg_lookupfails(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def xyzsomething(request):
                 return 42
 
             def test_func(some):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()  # "--collect-only")
         assert result.ret != 0
-        result.stdout.fnmatch_lines([
-            "*def test_func(some)*",
-            "*fixture*some*not found*",
-            "*xyzsomething*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*def test_func(some)*", "*fixture*some*not found*", "*xyzsomething*"]
+        )
 
     def test_funcarg_basic(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
 
             @pytest.fixture
             def some(request):
                 return request.function.__name__
             @pytest.fixture
             def other(request):
                 return 42
             def test_func(some, other):
                 pass
-        """)
+        """
+        )
         fixtures.fillfixtures(item)
         del item.funcargs["request"]
         assert len(get_public_names(item.funcargs)) == 2
-        assert item.funcargs['some'] == "test_func"
-        assert item.funcargs['other'] == 42
+        assert item.funcargs["some"] == "test_func"
+        assert item.funcargs["other"] == 42
 
     def test_funcarg_lookup_modulelevel(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def something(request):
                 return request.function.__name__
 
             class TestClass(object):
                 def test_method(self, something):
                     assert something == "test_method"
             def test_func(something):
                 assert something == "test_func"
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2)
 
     def test_funcarg_lookup_classlevel(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             class TestClass(object):
 
                 @pytest.fixture
                 def something(self, request):
                     return request.instance
 
                 def test_method(self, something):
                     assert something is self
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            "*1 passed*"
-        ])
+        result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_conftest_funcargs_only_available_in_subdir(self, testdir):
         sub1 = testdir.mkpydir("sub1")
         sub2 = testdir.mkpydir("sub2")
-        sub1.join("conftest.py").write(_pytest._code.Source("""
+        sub1.join("conftest.py").write(
+            _pytest._code.Source(
+                """
             import pytest
             @pytest.fixture
             def arg1(request):
                 pytest.raises(Exception, "request.getfixturevalue('arg2')")
-        """))
-        sub2.join("conftest.py").write(_pytest._code.Source("""
+        """
+            )
+        )
+        sub2.join("conftest.py").write(
+            _pytest._code.Source(
+                """
             import pytest
             @pytest.fixture
             def arg2(request):
                 pytest.raises(Exception, "request.getfixturevalue('arg1')")
-        """))
+        """
+            )
+        )
 
         sub1.join("test_in_sub1.py").write("def test_1(arg1): pass")
         sub2.join("test_in_sub2.py").write("def test_2(arg2): pass")
         result = testdir.runpytest("-v")
         result.assert_outcomes(passed=2)
 
     def test_extend_fixture_module_class(self, testdir):
-        testfile = testdir.makepyfile("""
+        testfile = testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def spam():
                 return 'spam'
 
             class TestSpam(object):
 
                  @pytest.fixture
                  def spam(self, spam):
                      return spam * 2
 
                  def test_spam(self, spam):
                      assert spam == 'spamspam'
-        """)
+        """
+        )
         result = testdir.runpytest()
         result.stdout.fnmatch_lines(["*1 passed*"])
         result = testdir.runpytest(testfile)
         result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_extend_fixture_conftest_module(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture
             def spam():
                 return 'spam'
-        """)
-        testfile = testdir.makepyfile("""
+        """
+        )
+        testfile = testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def spam(spam):
                 return spam * 2
 
             def test_spam(spam):
                 assert spam == 'spamspam'
-        """)
+        """
+        )
         result = testdir.runpytest()
         result.stdout.fnmatch_lines(["*1 passed*"])
         result = testdir.runpytest(testfile)
         result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_extend_fixture_conftest_conftest(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture
             def spam():
                 return 'spam'
-        """)
+        """
+        )
         pkg = testdir.mkpydir("pkg")
-        pkg.join("conftest.py").write(_pytest._code.Source("""
+        pkg.join("conftest.py").write(
+            _pytest._code.Source(
+                """
             import pytest
 
             @pytest.fixture
             def spam(spam):
                 return spam * 2
-        """))
+        """
+            )
+        )
         testfile = pkg.join("test_spam.py")
-        testfile.write(_pytest._code.Source("""
+        testfile.write(
+            _pytest._code.Source(
+                """
             def test_spam(spam):
                 assert spam == "spamspam"
-        """))
+        """
+            )
+        )
         result = testdir.runpytest()
         result.stdout.fnmatch_lines(["*1 passed*"])
         result = testdir.runpytest(testfile)
         result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_extend_fixture_conftest_plugin(self, testdir):
-        testdir.makepyfile(testplugin="""
+        testdir.makepyfile(
+            testplugin="""
             import pytest
 
             @pytest.fixture
             def foo():
                 return 7
-        """)
+        """
+        )
         testdir.syspathinsert()
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
 
             pytest_plugins = 'testplugin'
 
             @pytest.fixture
             def foo(foo):
                 return foo + 7
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             def test_foo(foo):
                 assert foo == 14
-        """)
-        result = testdir.runpytest('-s')
+        """
+        )
+        result = testdir.runpytest("-s")
         assert result.ret == 0
 
     def test_extend_fixture_plugin_plugin(self, testdir):
         # Two plugins should extend each order in loading order
-        testdir.makepyfile(testplugin0="""
+        testdir.makepyfile(
+            testplugin0="""
             import pytest
 
             @pytest.fixture
             def foo():
                 return 7
-        """)
-        testdir.makepyfile(testplugin1="""
+        """
+        )
+        testdir.makepyfile(
+            testplugin1="""
             import pytest
 
             @pytest.fixture
             def foo(foo):
                 return foo + 7
-        """)
+        """
+        )
         testdir.syspathinsert()
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             pytest_plugins = ['testplugin0', 'testplugin1']
 
             def test_foo(foo):
                 assert foo == 14
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == 0
 
     def test_override_parametrized_fixture_conftest_module(self, testdir):
         """Test override of the parametrized fixture with non-parametrized one on the test module level."""
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture(params=[1, 2, 3])
             def spam(request):
                 return request.param
-        """)
-        testfile = testdir.makepyfile("""
+        """
+        )
+        testfile = testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def spam():
                 return 'spam'
 
             def test_spam(spam):
                 assert spam == 'spam'
-        """)
+        """
+        )
         result = testdir.runpytest()
         result.stdout.fnmatch_lines(["*1 passed*"])
         result = testdir.runpytest(testfile)
         result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_override_parametrized_fixture_conftest_conftest(self, testdir):
         """Test override of the parametrized fixture with non-parametrized one on the conftest level."""
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture(params=[1, 2, 3])
             def spam(request):
                 return request.param
-        """)
-        subdir = testdir.mkpydir('subdir')
-        subdir.join("conftest.py").write(_pytest._code.Source("""
+        """
+        )
+        subdir = testdir.mkpydir("subdir")
+        subdir.join("conftest.py").write(
+            _pytest._code.Source(
+                """
             import pytest
 
             @pytest.fixture
             def spam():
                 return 'spam'
-        """))
+        """
+            )
+        )
         testfile = subdir.join("test_spam.py")
-        testfile.write(_pytest._code.Source("""
+        testfile.write(
+            _pytest._code.Source(
+                """
             def test_spam(spam):
                 assert spam == "spam"
-        """))
+        """
+            )
+        )
         result = testdir.runpytest()
         result.stdout.fnmatch_lines(["*1 passed*"])
         result = testdir.runpytest(testfile)
         result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_override_non_parametrized_fixture_conftest_module(self, testdir):
         """Test override of the non-parametrized fixture with parametrized one on the test module level."""
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture
             def spam():
                 return 'spam'
-        """)
-        testfile = testdir.makepyfile("""
+        """
+        )
+        testfile = testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(params=[1, 2, 3])
             def spam(request):
                 return request.param
 
             params = {'spam': 1}
 
             def test_spam(spam):
                 assert spam == params['spam']
                 params['spam'] += 1
-        """)
+        """
+        )
         result = testdir.runpytest()
         result.stdout.fnmatch_lines(["*3 passed*"])
         result = testdir.runpytest(testfile)
         result.stdout.fnmatch_lines(["*3 passed*"])
 
     def test_override_non_parametrized_fixture_conftest_conftest(self, testdir):
         """Test override of the non-parametrized fixture with parametrized one on the conftest level."""
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture
             def spam():
                 return 'spam'
-        """)
-        subdir = testdir.mkpydir('subdir')
-        subdir.join("conftest.py").write(_pytest._code.Source("""
+        """
+        )
+        subdir = testdir.mkpydir("subdir")
+        subdir.join("conftest.py").write(
+            _pytest._code.Source(
+                """
             import pytest
 
             @pytest.fixture(params=[1, 2, 3])
             def spam(request):
                 return request.param
-        """))
+        """
+            )
+        )
         testfile = subdir.join("test_spam.py")
-        testfile.write(_pytest._code.Source("""
+        testfile.write(
+            _pytest._code.Source(
+                """
             params = {'spam': 1}
 
             def test_spam(spam):
                 assert spam == params['spam']
                 params['spam'] += 1
-        """))
+        """
+            )
+        )
         result = testdir.runpytest()
         result.stdout.fnmatch_lines(["*3 passed*"])
         result = testdir.runpytest(testfile)
         result.stdout.fnmatch_lines(["*3 passed*"])
 
-    def test_override_autouse_fixture_with_parametrized_fixture_conftest_conftest(self, testdir):
+    def test_override_autouse_fixture_with_parametrized_fixture_conftest_conftest(
+        self, testdir
+    ):
         """Test override of the autouse fixture with parametrized one on the conftest level.
         This test covers the issue explained in issue 1601
         """
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture(autouse=True)
             def spam():
                 return 'spam'
-        """)
-        subdir = testdir.mkpydir('subdir')
-        subdir.join("conftest.py").write(_pytest._code.Source("""
+        """
+        )
+        subdir = testdir.mkpydir("subdir")
+        subdir.join("conftest.py").write(
+            _pytest._code.Source(
+                """
             import pytest
 
             @pytest.fixture(params=[1, 2, 3])
             def spam(request):
                 return request.param
-        """))
+        """
+            )
+        )
         testfile = subdir.join("test_spam.py")
-        testfile.write(_pytest._code.Source("""
+        testfile.write(
+            _pytest._code.Source(
+                """
             params = {'spam': 1}
 
             def test_spam(spam):
                 assert spam == params['spam']
                 params['spam'] += 1
-        """))
+        """
+            )
+        )
         result = testdir.runpytest()
         result.stdout.fnmatch_lines(["*3 passed*"])
         result = testdir.runpytest(testfile)
         result.stdout.fnmatch_lines(["*3 passed*"])
 
     def test_autouse_fixture_plugin(self, testdir):
         # A fixture from a plugin has no baseid set, which screwed up
         # the autouse fixture handling.
-        testdir.makepyfile(testplugin="""
+        testdir.makepyfile(
+            testplugin="""
             import pytest
 
             @pytest.fixture(autouse=True)
             def foo(request):
                 request.function.foo = 7
-        """)
+        """
+        )
         testdir.syspathinsert()
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             pytest_plugins = 'testplugin'
 
             def test_foo(request):
                 assert request.function.foo == 7
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == 0
 
     def test_funcarg_lookup_error(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture
             def a_fixture(): pass
 
             @pytest.fixture
             def b_fixture(): pass
 
             @pytest.fixture
             def c_fixture(): pass
 
             @pytest.fixture
             def d_fixture(): pass
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             def test_lookup_error(unknown):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*ERROR at setup of test_lookup_error*",
-            "  def test_lookup_error(unknown):*",
-            "E       fixture 'unknown' not found",
-            ">       available fixtures:*a_fixture,*b_fixture,*c_fixture,*d_fixture*monkeypatch,*",  # sorted
-            ">       use 'py*test --fixtures *' for help on them.",
-            "*1 error*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*ERROR at setup of test_lookup_error*",
+                "  def test_lookup_error(unknown):*",
+                "E       fixture 'unknown' not found",
+                ">       available fixtures:*a_fixture,*b_fixture,*c_fixture,*d_fixture*monkeypatch,*",  # sorted
+                ">       use 'py*test --fixtures *' for help on them.",
+                "*1 error*",
+            ]
+        )
         assert "INTERNAL" not in result.stdout.str()
 
     def test_fixture_excinfo_leak(self, testdir):
         # on python2 sys.excinfo would leak into fixture executions
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import sys
             import traceback
             import pytest
 
             @pytest.fixture
             def leak():
                 if sys.exc_info()[0]:  # python3 bug :)
                     traceback.print_exc()
                 #fails
                 assert sys.exc_info() == (None, None, None)
 
             def test_leak(leak):
                 if sys.exc_info()[0]:  # python3 bug :)
                     traceback.print_exc()
                 assert sys.exc_info() == (None, None, None)
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == 0
 
 
 class TestRequestBasic(object):
+
     def test_request_attributes(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
 
             @pytest.fixture
             def something(request): pass
             def test_func(something): pass
-        """)
+        """
+        )
         req = fixtures.FixtureRequest(item)
         assert req.function == item.obj
         assert req.keywords == item.keywords
-        assert hasattr(req.module, 'test_func')
+        assert hasattr(req.module, "test_func")
         assert req.cls is None
         assert req.function.__name__ == "test_func"
         assert req.config == item.config
         assert repr(req).find(req.function.__name__) != -1
 
     def test_request_attributes_method(self, testdir):
-        item, = testdir.getitems("""
+        item, = testdir.getitems(
+            """
             import pytest
             class TestB(object):
 
                 @pytest.fixture
                 def something(self, request):
                     return 1
                 def test_func(self, something):
                     pass
-        """)
+        """
+        )
         req = item._request
         assert req.cls.__name__ == "TestB"
         assert req.instance.__class__ == req.cls
 
     def test_request_contains_funcarg_arg2fixturedefs(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             import pytest
             @pytest.fixture
             def something(request):
                 pass
             class TestClass(object):
                 def test_method(self, something):
                     pass
-        """)
+        """
+        )
         item1, = testdir.genitems([modcol])
         assert item1.name == "test_method"
         arg2fixturedefs = fixtures.FixtureRequest(item1)._arg2fixturedefs
         assert len(arg2fixturedefs) == 1
-        assert arg2fixturedefs['something'][0].argname == "something"
+        assert arg2fixturedefs["something"][0].argname == "something"
+
+    def test_request_garbage(self, testdir):
+        testdir.makepyfile(
+            """
+            import sys
+            import pytest
+            from _pytest.fixtures import PseudoFixtureDef
+            import gc
+
+            @pytest.fixture(autouse=True)
+            def something(request):
+                # this method of test doesn't work on pypy
+                if hasattr(sys, "pypy_version_info"):
+                    yield
+                else:
+                    original = gc.get_debug()
+                    gc.set_debug(gc.DEBUG_SAVEALL)
+                    gc.collect()
+
+                    yield
+
+                    gc.collect()
+                    leaked_types = sum(1 for _ in gc.garbage
+                                       if isinstance(_, PseudoFixtureDef))
+
+                    gc.garbage[:] = []
+
+                    try:
+                        assert leaked_types == 0
+                    finally:
+                        gc.set_debug(original)
+
+            def test_func():
+                pass
+        """
+        )
+        reprec = testdir.inline_run()
+        reprec.assertoutcome(passed=1)
 
     def test_getfixturevalue_recursive(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture
             def something(request):
                 return 1
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def something(request):
                 return request.getfixturevalue("something") + 1
             def test_func(something):
                 assert something == 2
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
-    @pytest.mark.parametrize(
-        'getfixmethod', ('getfixturevalue', 'getfuncargvalue'))
+    @pytest.mark.parametrize("getfixmethod", ("getfixturevalue", "getfuncargvalue"))
     def test_getfixturevalue(self, testdir, getfixmethod):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             values = [2]
             @pytest.fixture
             def something(request): return 1
             @pytest.fixture
             def other(request):
                 return values.pop()
             def test_func(something): pass
-        """)
+        """
+        )
         import contextlib
-        if getfixmethod == 'getfuncargvalue':
+
+        if getfixmethod == "getfuncargvalue":
             warning_expectation = pytest.warns(DeprecationWarning)
         else:
             # see #1830 for a cleaner way to accomplish this
             @contextlib.contextmanager
             def expecting_no_warning():
                 yield
 
             warning_expectation = expecting_no_warning()
@@ -577,104 +727,117 @@ class TestRequestBasic(object):
             val2 = fixture_fetcher("other")  # see about caching
             assert val2 == 2
             pytest._fillfuncargs(item)
             assert item.funcargs["something"] == 1
             assert len(get_public_names(item.funcargs)) == 2
             assert "request" in item.funcargs
 
     def test_request_addfinalizer(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             teardownlist = []
             @pytest.fixture
             def something(request):
                 request.addfinalizer(lambda: teardownlist.append(1))
             def test_func(something): pass
-        """)
+        """
+        )
         item.session._setupstate.prepare(item)
         pytest._fillfuncargs(item)
         # successively check finalization calls
         teardownlist = item.getparent(pytest.Module).obj.teardownlist
         ss = item.session._setupstate
         assert not teardownlist
         ss.teardown_exact(item, None)
         print(ss.stack)
         assert teardownlist == [1]
 
     def test_mark_as_fixture_with_prefix_and_decorator_fails(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture
             def pytest_funcarg__marked_with_prefix_and_decorator():
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest_subprocess()
         assert result.ret != 0
-        result.stdout.fnmatch_lines([
-            "*AssertionError: fixtures cannot have*@pytest.fixture*",
-            "*pytest_funcarg__marked_with_prefix_and_decorator*"
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*AssertionError: fixtures cannot have*@pytest.fixture*",
+                "*pytest_funcarg__marked_with_prefix_and_decorator*",
+            ]
+        )
 
     def test_request_addfinalizer_failing_setup(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = [1]
             @pytest.fixture
             def myfix(request):
                 request.addfinalizer(values.pop)
                 assert 0
             def test_fix(myfix):
                 pass
             def test_finalizer_ran():
                 assert not values
-        """)
+        """
+        )
         reprec = testdir.inline_run("-s")
         reprec.assertoutcome(failed=1, passed=1)
 
     def test_request_addfinalizer_failing_setup_module(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = [1, 2]
             @pytest.fixture(scope="module")
             def myfix(request):
                 request.addfinalizer(values.pop)
                 request.addfinalizer(values.pop)
                 assert 0
             def test_fix(myfix):
                 pass
-        """)
+        """
+        )
         reprec = testdir.inline_run("-s")
         mod = reprec.getcalls("pytest_runtest_setup")[0].item.module
         assert not mod.values
 
     def test_request_addfinalizer_partial_setup_failure(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             values = []
             @pytest.fixture
             def something(request):
                 request.addfinalizer(lambda: values.append(None))
             def test_func(something, missingarg):
                 pass
             def test_second():
                 assert len(values) == 1
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            "*1 error*"  # XXX the whole module collection fails
-        ])
+        result.stdout.fnmatch_lines(
+            ["*1 error*"]  # XXX the whole module collection fails
+        )
 
     def test_request_subrequest_addfinalizer_exceptions(self, testdir):
         """
         Ensure exceptions raised during teardown by a finalizer are suppressed
         until all finalizers are called, re-raising the first exception (#2440)
         """
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             def _excepts(where):
                 raise Exception('Error in %s fixture' % where)
             @pytest.fixture
             def subrequest(request):
                 return request
             @pytest.fixture
@@ -685,69 +848,74 @@ class TestRequestBasic(object):
             @pytest.fixture
             def excepts(subrequest):
                 subrequest.addfinalizer(lambda: _excepts('excepts'))
                 subrequest.addfinalizer(lambda: values.append(3))
             def test_first(something, excepts):
                 pass
             def test_second():
                 assert values == [3, 2, 1]
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            '*Exception: Error in excepts fixture',
-            '* 2 passed, 1 error in *',
-        ])
+        result.stdout.fnmatch_lines(
+            ["*Exception: Error in excepts fixture", "* 2 passed, 1 error in *"]
+        )
 
     def test_request_getmodulepath(self, testdir):
         modcol = testdir.getmodulecol("def test_somefunc(): pass")
         item, = testdir.genitems([modcol])
         req = fixtures.FixtureRequest(item)
         assert req.fspath == modcol.fspath
 
     def test_request_fixturenames(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             from _pytest.pytester import get_public_names
             @pytest.fixture()
             def arg1():
                 pass
             @pytest.fixture()
             def farg(arg1):
                 pass
             @pytest.fixture(autouse=True)
             def sarg(tmpdir):
                 pass
             def test_function(request, farg):
                 assert set(get_public_names(request.fixturenames)) == \
                        set(["tmpdir", "sarg", "arg1", "request", "farg",
                             "tmpdir_factory"])
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_funcargnames_compatattr(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def pytest_generate_tests(metafunc):
                 assert metafunc.funcargnames == metafunc.fixturenames
             @pytest.fixture
             def fn(request):
                 assert request._pyfuncitem.funcargnames == \
                        request._pyfuncitem.fixturenames
                 return request.funcargnames, request.fixturenames
 
             def test_hello(fn):
                 assert fn[0] == fn[1]
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_setupdecorator_and_xunit(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             @pytest.fixture(scope='module', autouse=True)
             def setup_module():
                 values.append("module")
             @pytest.fixture(autouse=True)
             def setup_function():
                 values.append("function")
@@ -762,170 +930,195 @@ class TestRequestBasic(object):
                 @pytest.fixture(autouse=True)
                 def setup_method(self):
                     values.append("method")
                 def test_method(self):
                     pass
             def test_all():
                 assert values == ["module", "function", "class",
                              "function", "method", "function"]
-        """)
+        """
+        )
         reprec = testdir.inline_run("-v")
         reprec.assertoutcome(passed=3)
 
     def test_fixtures_sub_subdir_normalize_sep(self, testdir):
         # this tests that normalization of nodeids takes place
         b = testdir.mkdir("tests").mkdir("unit")
-        b.join("conftest.py").write(_pytest._code.Source("""
+        b.join("conftest.py").write(
+            _pytest._code.Source(
+                """
             import pytest
             @pytest.fixture
             def arg1():
                 pass
-        """))
+        """
+            )
+        )
         p = b.join("test_module.py")
         p.write("def test_func(arg1): pass")
         result = testdir.runpytest(p, "--fixtures")
         assert result.ret == 0
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *fixtures defined*conftest*
             *arg1*
-        """)
+        """
+        )
 
     def test_show_fixtures_color_yes(self, testdir):
         testdir.makepyfile("def test_this(): assert 1")
-        result = testdir.runpytest('--color=yes', '--fixtures')
-        assert '\x1b[32mtmpdir' in result.stdout.str()
+        result = testdir.runpytest("--color=yes", "--fixtures")
+        assert "\x1b[32mtmpdir" in result.stdout.str()
 
     def test_newstyle_with_request(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture()
             def arg(request):
                 pass
             def test_1(arg):
                 pass
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_setupcontext_no_param(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(params=[1,2])
             def arg(request):
                 return request.param
 
             @pytest.fixture(autouse=True)
             def mysetup(request, arg):
                 assert not hasattr(request, "param")
             def test_1(arg):
                 assert arg in (1,2)
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2)
 
 
 class TestRequestMarking(object):
+
     def test_applymarker(self, testdir):
-        item1, item2 = testdir.getitems("""
+        item1, item2 = testdir.getitems(
+            """
             import pytest
 
             @pytest.fixture
             def something(request):
                 pass
             class TestClass(object):
                 def test_func1(self, something):
                     pass
                 def test_func2(self, something):
                     pass
-        """)
+        """
+        )
         req1 = fixtures.FixtureRequest(item1)
-        assert 'xfail' not in item1.keywords
+        assert "xfail" not in item1.keywords
         req1.applymarker(pytest.mark.xfail)
-        assert 'xfail' in item1.keywords
-        assert 'skipif' not in item1.keywords
+        assert "xfail" in item1.keywords
+        assert "skipif" not in item1.keywords
         req1.applymarker(pytest.mark.skipif)
-        assert 'skipif' in item1.keywords
+        assert "skipif" in item1.keywords
         pytest.raises(ValueError, "req1.applymarker(42)")
 
     def test_accesskeywords(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture()
             def keywords(request):
                 return request.keywords
             @pytest.mark.XYZ
             def test_function(keywords):
                 assert keywords["XYZ"]
                 assert "abc" not in keywords
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_accessmarker_dynamic(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             @pytest.fixture()
             def keywords(request):
                 return request.keywords
 
             @pytest.fixture(scope="class", autouse=True)
             def marking(request):
                 request.applymarker(pytest.mark.XYZ("hello"))
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             import pytest
             def test_fun1(keywords):
                 assert keywords["XYZ"] is not None
                 assert "abc" not in keywords
             def test_fun2(keywords):
                 assert keywords["XYZ"] is not None
                 assert "abc" not in keywords
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2)
 
 
 class TestRequestCachedSetup(object):
+
     def test_request_cachedsetup_defaultmodule(self, testdir):
-        reprec = testdir.inline_runsource("""
+        reprec = testdir.inline_runsource(
+            """
             mysetup = ["hello",].pop
 
             import pytest
 
             @pytest.fixture
             def something(request):
                 return request.cached_setup(mysetup, scope="module")
 
             def test_func1(something):
                 assert something == "hello"
             class TestClass(object):
                 def test_func1a(self, something):
                     assert something == "hello"
-        """)
+        """
+        )
         reprec.assertoutcome(passed=2)
 
     def test_request_cachedsetup_class(self, testdir):
-        reprec = testdir.inline_runsource("""
+        reprec = testdir.inline_runsource(
+            """
             mysetup = ["hello", "hello2", "hello3"].pop
 
             import pytest
             @pytest.fixture
             def something(request):
                 return request.cached_setup(mysetup, scope="class")
             def test_func1(something):
                 assert something == "hello3"
             def test_func2(something):
                 assert something == "hello2"
             class TestClass(object):
                 def test_func1a(self, something):
                     assert something == "hello"
                 def test_func2b(self, something):
                     assert something == "hello"
-        """)
+        """
+        )
         reprec.assertoutcome(passed=4)
 
     def test_request_cachedsetup_extrakey(self, testdir):
         item1 = testdir.getitem("def test_func(): pass")
         req1 = fixtures.FixtureRequest(item1)
         values = ["hello", "world"]
 
         def setup():
@@ -947,281 +1140,304 @@ class TestRequestCachedSetup(object):
 
         def setup():
             values.append("setup")
 
         def teardown(val):
             values.append("teardown")
 
         req1.cached_setup(setup, teardown, scope="function")
-        assert values == ['setup']
+        assert values == ["setup"]
         # artificial call of finalizer
         setupstate = req1._pyfuncitem.session._setupstate
         setupstate._callfinalizers(item1)
         assert values == ["setup", "teardown"]
         req1.cached_setup(setup, teardown, scope="function")
         assert values == ["setup", "teardown", "setup"]
         setupstate._callfinalizers(item1)
         assert values == ["setup", "teardown", "setup", "teardown"]
 
     def test_request_cached_setup_two_args(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def arg1(request):
                 return request.cached_setup(lambda: 42)
             @pytest.fixture
             def arg2(request):
                 return request.cached_setup(lambda: 17)
             def test_two_different_setups(arg1, arg2):
                 assert arg1 != arg2
-        """)
+        """
+        )
         result = testdir.runpytest("-v")
-        result.stdout.fnmatch_lines([
-            "*1 passed*"
-        ])
+        result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_request_cached_setup_getfixturevalue(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def arg1(request):
                 arg1 = request.getfixturevalue("arg2")
                 return request.cached_setup(lambda: arg1 + 1)
             @pytest.fixture
             def arg2(request):
                 return request.cached_setup(lambda: 10)
             def test_two_funcarg(arg1):
                 assert arg1 == 11
-        """)
+        """
+        )
         result = testdir.runpytest("-v")
-        result.stdout.fnmatch_lines([
-            "*1 passed*"
-        ])
+        result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_request_cached_setup_functional(self, testdir):
-        testdir.makepyfile(test_0="""
+        testdir.makepyfile(
+            test_0="""
             import pytest
             values = []
             @pytest.fixture
             def something(request):
                 val = request.cached_setup(fsetup, fteardown)
                 return val
             def fsetup(mycache=[1]):
                 values.append(mycache.pop())
                 return values
             def fteardown(something):
                 values.remove(something[0])
                 values.append(2)
             def test_list_once(something):
                 assert something == [1]
             def test_list_twice(something):
                 assert something == [1]
-        """)
-        testdir.makepyfile(test_1="""
+        """
+        )
+        testdir.makepyfile(
+            test_1="""
             import test_0 # should have run already
             def test_check_test0_has_teardown_correct():
                 assert test_0.values == [2]
-        """)
+        """
+        )
         result = testdir.runpytest("-v")
-        result.stdout.fnmatch_lines([
-            "*3 passed*"
-        ])
+        result.stdout.fnmatch_lines(["*3 passed*"])
 
     def test_issue117_sessionscopeteardown(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def app(request):
                 app = request.cached_setup(
                     scope='session',
                     setup=lambda: 0,
                     teardown=lambda x: 3/x)
                 return app
             def test_func(app):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret != 0
-        result.stdout.fnmatch_lines([
-            "*3/x*",
-            "*ZeroDivisionError*",
-        ])
+        result.stdout.fnmatch_lines(["*3/x*", "*ZeroDivisionError*"])
 
 
 class TestFixtureUsages(object):
+
     def test_noargfixturedec(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture
             def arg1():
                 return 1
 
             def test_func(arg1):
                 assert arg1 == 1
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_receives_funcargs(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture()
             def arg1():
                 return 1
 
             @pytest.fixture()
             def arg2(arg1):
                 return arg1 + 1
 
             def test_add(arg2):
                 assert arg2 == 2
             def test_all(arg1, arg2):
                 assert arg1 == 1
                 assert arg2 == 2
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2)
 
     def test_receives_funcargs_scope_mismatch(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(scope="function")
             def arg1():
                 return 1
 
             @pytest.fixture(scope="module")
             def arg2(arg1):
                 return arg1 + 1
 
             def test_add(arg2):
                 assert arg2 == 2
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*ScopeMismatch*involved factories*",
-            "* def arg2*",
-            "* def arg1*",
-            "*1 error*"
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*ScopeMismatch*involved factories*",
+                "* def arg2*",
+                "* def arg1*",
+                "*1 error*",
+            ]
+        )
 
     def test_receives_funcargs_scope_mismatch_issue660(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(scope="function")
             def arg1():
                 return 1
 
             @pytest.fixture(scope="module")
             def arg2(arg1):
                 return arg1 + 1
 
             def test_add(arg1, arg2):
                 assert arg2 == 2
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*ScopeMismatch*involved factories*",
-            "* def arg2*",
-            "*1 error*"
-        ])
+        result.stdout.fnmatch_lines(
+            ["*ScopeMismatch*involved factories*", "* def arg2*", "*1 error*"]
+        )
 
     def test_invalid_scope(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(scope="functions")
             def badscope():
                 pass
 
             def test_nothing(badscope):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest_inprocess()
         result.stdout.fnmatch_lines(
-            ("*ValueError: fixture badscope from test_invalid_scope.py has an unsupported"
-             " scope value 'functions'")
+            (
+                "*ValueError: fixture badscope from test_invalid_scope.py has an unsupported"
+                " scope value 'functions'"
+            )
         )
 
     def test_funcarg_parametrized_and_used_twice(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             @pytest.fixture(params=[1,2])
             def arg1(request):
                 values.append(1)
                 return request.param
 
             @pytest.fixture()
             def arg2(arg1):
                 return arg1 + 1
 
             def test_add(arg1, arg2):
                 assert arg2 == arg1 + 1
                 assert len(values) == arg1
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*2 passed*"
-        ])
+        result.stdout.fnmatch_lines(["*2 passed*"])
 
     def test_factory_uses_unknown_funcarg_as_dependency_error(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture()
             def fail(missing):
                 return
 
             @pytest.fixture()
             def call_fail(fail):
                 return
 
             def test_missing(call_fail):
                 pass
-            """)
+            """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *pytest.fixture()*
             *def call_fail(fail)*
             *pytest.fixture()*
             *def fail*
             *fixture*'missing'*not found*
-        """)
+        """
+        )
 
     def test_factory_setup_as_classes_fails(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             class arg1(object):
                 def __init__(self, request):
                     self.x = 1
             arg1 = pytest.fixture()(arg1)
 
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         values = reprec.getfailedcollections()
         assert len(values) == 1
 
     def test_request_can_be_overridden(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture()
             def request(request):
                 request.a = 1
                 return request
             def test_request(request):
                 assert request.a == 1
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_usefixtures_marker(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             values = []
 
             @pytest.fixture(scope="class")
             def myfix(request):
                 request.cls.hello = "world"
                 values.append(1)
@@ -1229,66 +1445,78 @@ class TestFixtureUsages(object):
             class TestClass(object):
                 def test_one(self):
                     assert self.hello == "world"
                     assert len(values) == 1
                 def test_two(self):
                     assert self.hello == "world"
                     assert len(values) == 1
             pytest.mark.usefixtures("myfix")(TestClass)
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2)
 
     def test_usefixtures_ini(self, testdir):
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
             usefixtures = myfix
-        """)
-        testdir.makeconftest("""
+        """
+        )
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture(scope="class")
             def myfix(request):
                 request.cls.hello = "world"
 
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             class TestClass(object):
                 def test_one(self):
                     assert self.hello == "world"
                 def test_two(self):
                     assert self.hello == "world"
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2)
 
     def test_usefixtures_seen_in_showmarkers(self, testdir):
         result = testdir.runpytest("--markers")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *usefixtures(fixturename1*mark tests*fixtures*
-        """)
+        """
+        )
 
     def test_request_instance_issue203(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             class TestClass(object):
                 @pytest.fixture
                 def setup1(self, request):
                     assert self == request.instance
                     self.arg1 = 1
                 def test_hello(self, setup1):
                     assert self.arg1 == 1
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_fixture_parametrized_with_iterator(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             values = []
             def f():
                 yield 1
                 yield 2
             dec = pytest.fixture(scope="module", params=f())
 
@@ -1298,132 +1526,158 @@ class TestFixtureUsages(object):
             @dec
             def arg2(request):
                 return request.param
 
             def test_1(arg):
                 values.append(arg)
             def test_2(arg2):
                 values.append(arg2*10)
-        """)
+        """
+        )
         reprec = testdir.inline_run("-v")
         reprec.assertoutcome(passed=4)
         values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
         assert values == [1, 2, 10, 20]
 
 
 class TestFixtureManagerParseFactories(object):
 
     @pytest.fixture
     def testdir(self, request):
         testdir = request.getfixturevalue("testdir")
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture
             def hello(request):
                 return "conftest"
 
             @pytest.fixture
             def fm(request):
                 return request._fixturemanager
 
             @pytest.fixture
             def item(request):
                 return request._pyfuncitem
-        """)
+        """
+        )
         return testdir
 
     def test_parsefactories_evil_objects_issue214(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             class A(object):
                 def __call__(self):
                     pass
                 def __getattr__(self, name):
                     raise RuntimeError()
             a = A()
             def test_hello():
                 pass
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1, failed=0)
 
     def test_parsefactories_conftest(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_hello(item, fm):
                 for name in ("fm", "hello", "item"):
                     faclist = fm.getfixturedefs(name, item.nodeid)
                     assert len(faclist) == 1
                     fac = faclist[0]
                     assert fac.func.__name__ == name
-        """)
+        """
+        )
         reprec = testdir.inline_run("-s")
         reprec.assertoutcome(passed=1)
 
     def test_parsefactories_conftest_and_module_and_class(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def hello(request):
                 return "module"
             class TestClass(object):
                 @pytest.fixture
                 def hello(self, request):
                     return "class"
                 def test_hello(self, item, fm):
                     faclist = fm.getfixturedefs("hello", item.nodeid)
                     print (faclist)
                     assert len(faclist) == 3
                     assert faclist[0].func(item._request) == "conftest"
                     assert faclist[1].func(item._request) == "module"
                     assert faclist[2].func(item._request) == "class"
-        """)
+        """
+        )
         reprec = testdir.inline_run("-s")
         reprec.assertoutcome(passed=1)
 
     def test_parsefactories_relative_node_ids(self, testdir):
         # example mostly taken from:
         # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html
         runner = testdir.mkdir("runner")
         package = testdir.mkdir("package")
-        package.join("conftest.py").write(dedent("""\
+        package.join("conftest.py").write(
+            dedent(
+                """\
             import pytest
             @pytest.fixture
             def one():
                 return 1
-        """))
-        package.join("test_x.py").write(dedent("""\
+        """
+            )
+        )
+        package.join("test_x.py").write(
+            dedent(
+                """\
             def test_x(one):
                 assert one == 1
-        """))
+        """
+            )
+        )
         sub = package.mkdir("sub")
         sub.join("__init__.py").ensure()
-        sub.join("conftest.py").write(dedent("""\
+        sub.join("conftest.py").write(
+            dedent(
+                """\
             import pytest
             @pytest.fixture
             def one():
                 return 2
-        """))
-        sub.join("test_y.py").write(dedent("""\
+        """
+            )
+        )
+        sub.join("test_y.py").write(
+            dedent(
+                """\
             def test_x(one):
                 assert one == 2
-        """))
+        """
+            )
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2)
         with runner.as_cwd():
             reprec = testdir.inline_run("..")
             reprec.assertoutcome(passed=2)
 
 
 class TestAutouseDiscovery(object):
 
     @pytest.fixture
     def testdir(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             @pytest.fixture(autouse=True)
             def perfunction(request, tmpdir):
                 pass
 
             @pytest.fixture()
             def arg1(tmpdir):
                 pass
@@ -1433,70 +1687,78 @@ class TestAutouseDiscovery(object):
 
             @pytest.fixture
             def fm(request):
                 return request._fixturemanager
 
             @pytest.fixture
             def item(request):
                 return request._pyfuncitem
-        """)
+        """
+        )
         return testdir
 
     def test_parsefactories_conftest(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             from _pytest.pytester import get_public_names
             def test_check_setup(item, fm):
                 autousenames = fm._getautousenames(item.nodeid)
                 assert len(get_public_names(autousenames)) == 2
                 assert "perfunction2" in autousenames
                 assert "perfunction" in autousenames
-        """)
+        """
+        )
         reprec = testdir.inline_run("-s")
         reprec.assertoutcome(passed=1)
 
     def test_two_classes_separated_autouse(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             class TestA(object):
                 values = []
                 @pytest.fixture(autouse=True)
                 def setup1(self):
                     self.values.append(1)
                 def test_setup1(self):
                     assert self.values == [1]
             class TestB(object):
                 values = []
                 @pytest.fixture(autouse=True)
                 def setup2(self):
                     self.values.append(1)
                 def test_setup2(self):
                     assert self.values == [1]
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2)
 
     def test_setup_at_classlevel(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             class TestClass(object):
                 @pytest.fixture(autouse=True)
                 def permethod(self, request):
                     request.instance.funcname = request.function.__name__
                 def test_method1(self):
                     assert self.funcname == "test_method1"
                 def test_method2(self):
                     assert self.funcname == "test_method2"
-        """)
+        """
+        )
         reprec = testdir.inline_run("-s")
         reprec.assertoutcome(passed=2)
 
     @pytest.mark.xfail(reason="'enabled' feature not implemented")
     def test_setup_enabled_functionnode(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             def enabled(parentnode, markers):
                 return "needsdb" in markers
 
             @pytest.fixture(params=[1,2])
             def db(request):
                 return request.param
@@ -1506,56 +1768,64 @@ class TestAutouseDiscovery(object):
                 pass
 
             def test_func1(request):
                 assert "db" not in request.fixturenames
 
             @pytest.mark.needsdb
             def test_func2(request):
                 assert "db" in request.fixturenames
-        """)
+        """
+        )
         reprec = testdir.inline_run("-s")
         reprec.assertoutcome(passed=2)
 
     def test_callables_nocode(self, testdir):
         """
-        a imported mock.call would break setup/factory discovery
+        an imported mock.call would break setup/factory discovery
         due to it being callable and __code__ not being a code object
         """
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
            class _call(tuple):
                def __call__(self, *k, **kw):
                    pass
                def __getattr__(self, k):
                    return self
 
            call = _call()
-        """)
+        """
+        )
         reprec = testdir.inline_run("-s")
         reprec.assertoutcome(failed=0, passed=0)
 
     def test_autouse_in_conftests(self, testdir):
         a = testdir.mkdir("a")
         b = testdir.mkdir("a1")
-        conftest = testdir.makeconftest("""
+        conftest = testdir.makeconftest(
+            """
             import pytest
             @pytest.fixture(autouse=True)
             def hello():
                 xxx
-        """)
+        """
+        )
         conftest.move(a.join(conftest.basename))
         a.join("test_something.py").write("def test_func(): pass")
         b.join("test_otherthing.py").write("def test_func(): pass")
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *1 passed*1 error*
-        """)
+        """
+        )
 
     def test_autouse_in_module_and_two_classes(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             @pytest.fixture(autouse=True)
             def append1():
                 values.append("module")
             def test_x():
                 assert values == ["module"]
 
@@ -1563,58 +1833,71 @@ class TestAutouseDiscovery(object):
                 @pytest.fixture(autouse=True)
                 def append2(self):
                     values.append("A")
                 def test_hello(self):
                     assert values == ["module", "module", "A"], values
             class TestA2(object):
                 def test_world(self):
                     assert values == ["module", "module", "A", "module"], values
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=3)
 
 
 class TestAutouseManagement(object):
+
     def test_autouse_conftest_mid_directory(self, testdir):
         pkgdir = testdir.mkpydir("xyz123")
-        pkgdir.join("conftest.py").write(_pytest._code.Source("""
+        pkgdir.join("conftest.py").write(
+            _pytest._code.Source(
+                """
             import pytest
             @pytest.fixture(autouse=True)
             def app():
                 import sys
                 sys._myapp = "hello"
-        """))
+        """
+            )
+        )
         t = pkgdir.ensure("tests", "test_app.py")
-        t.write(_pytest._code.Source("""
+        t.write(
+            _pytest._code.Source(
+                """
             import sys
             def test_app():
                 assert sys._myapp == "hello"
-        """))
+        """
+            )
+        )
         reprec = testdir.inline_run("-s")
         reprec.assertoutcome(passed=1)
 
     def test_autouse_honored_for_yield(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(autouse=True)
             def tst():
                 global x
                 x = 3
             def test_gen():
                 def f(hello):
                     assert x == abs(hello)
                 yield f, 3
                 yield f, -3
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2)
 
     def test_funcarg_and_setup(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             @pytest.fixture(scope="module")
             def arg():
                 values.append(1)
                 return 0
             @pytest.fixture(scope="module", autouse=True)
             def something(arg):
@@ -1624,22 +1907,24 @@ class TestAutouseManagement(object):
                 assert len(values) == 2
                 assert values == [1,2]
                 assert arg == 0
 
             def test_hello2(arg):
                 assert len(values) == 2
                 assert values == [1,2]
                 assert arg == 0
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2)
 
     def test_uses_parametrized_resource(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             @pytest.fixture(params=[1,2])
             def arg(request):
                 return request.param
 
             @pytest.fixture(autouse=True)
             def something(arg):
@@ -1648,22 +1933,24 @@ class TestAutouseManagement(object):
             def test_hello():
                 if len(values) == 1:
                     assert values == [1]
                 elif len(values) == 2:
                     assert values == [1, 2]
                 else:
                     0/0
 
-        """)
+        """
+        )
         reprec = testdir.inline_run("-s")
         reprec.assertoutcome(passed=2)
 
     def test_session_parametrized_function(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             values = []
 
             @pytest.fixture(scope="session", params=[1,2])
             def arg(request):
                return request.param
 
@@ -1673,22 +1960,24 @@ class TestAutouseManagement(object):
                     values.append(arg)
 
             def test_some():
                 pass
 
             def test_result(arg):
                 assert len(values) == arg
                 assert values[:arg] == [1,2][:arg]
-        """)
+        """
+        )
         reprec = testdir.inline_run("-v", "-s")
         reprec.assertoutcome(passed=4)
 
     def test_class_function_parametrization_finalization(self, testdir):
-        p = testdir.makeconftest("""
+        p = testdir.makeconftest(
+            """
             import pytest
             import pprint
 
             values = []
 
             @pytest.fixture(scope="function", params=[1,2])
             def farg(request):
                 return request.param
@@ -1697,217 +1986,247 @@ class TestAutouseManagement(object):
             def carg(request):
                 return request.param
 
             @pytest.fixture(scope="function", autouse=True)
             def append(request, farg, carg):
                 def fin():
                     values.append("fin_%s%s" % (carg, farg))
                 request.addfinalizer(fin)
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             import pytest
 
             class TestClass(object):
                 def test_1(self):
                     pass
             class TestClass2(object):
                 def test_2(self):
                     pass
-        """)
-        confcut = "--confcutdir={0}".format(testdir.tmpdir)
+        """
+        )
+        confcut = "--confcutdir={}".format(testdir.tmpdir)
         reprec = testdir.inline_run("-v", "-s", confcut)
         reprec.assertoutcome(passed=8)
         config = reprec.getcalls("pytest_unconfigure")[0].config
         values = config.pluginmanager._getconftestmodules(p)[0].values
         assert values == ["fin_a1", "fin_a2", "fin_b1", "fin_b2"] * 2
 
     def test_scope_ordering(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             @pytest.fixture(scope="function", autouse=True)
             def fappend2():
                 values.append(2)
             @pytest.fixture(scope="class", autouse=True)
             def classappend3():
                 values.append(3)
             @pytest.fixture(scope="module", autouse=True)
             def mappend():
                 values.append(1)
 
             class TestHallo(object):
                 def test_method(self):
                     assert values == [1,3,2]
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_parametrization_setup_teardown_ordering(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             def pytest_generate_tests(metafunc):
+                if metafunc.cls is None:
+                    assert metafunc.function is test_finish
                 if metafunc.cls is not None:
                     metafunc.parametrize("item", [1,2], scope="class")
             class TestClass(object):
                 @pytest.fixture(scope="class", autouse=True)
                 def addteardown(self, item, request):
                     values.append("setup-%d" % item)
                     request.addfinalizer(lambda: values.append("teardown-%d" % item))
                 def test_step1(self, item):
                     values.append("step1-%d" % item)
                 def test_step2(self, item):
                     values.append("step2-%d" % item)
 
             def test_finish():
                 print (values)
                 assert values == ["setup-1", "step1-1", "step2-1", "teardown-1",
                              "setup-2", "step1-2", "step2-2", "teardown-2",]
-        """)
-        reprec = testdir.inline_run()
+        """
+        )
+        reprec = testdir.inline_run("-s")
         reprec.assertoutcome(passed=5)
 
     def test_ordering_autouse_before_explicit(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             values = []
             @pytest.fixture(autouse=True)
             def fix1():
                 values.append(1)
             @pytest.fixture()
             def arg1():
                 values.append(2)
             def test_hello(arg1):
                 assert values == [1,2]
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     @pytest.mark.issue226
     @pytest.mark.parametrize("param1", ["", "params=[1]"], ids=["p00", "p01"])
     @pytest.mark.parametrize("param2", ["", "params=[1]"], ids=["p10", "p11"])
     def test_ordering_dependencies_torndown_first(self, testdir, param1, param2):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             @pytest.fixture(%(param1)s)
             def arg1(request):
                 request.addfinalizer(lambda: values.append("fin1"))
                 values.append("new1")
             @pytest.fixture(%(param2)s)
             def arg2(request, arg1):
                 request.addfinalizer(lambda: values.append("fin2"))
                 values.append("new2")
 
             def test_arg(arg2):
                 pass
             def test_check():
                 assert values == ["new1", "new2", "fin2", "fin1"]
-        """ % locals())
+        """
+            % locals()
+        )
         reprec = testdir.inline_run("-s")
         reprec.assertoutcome(passed=2)
 
 
 class TestFixtureMarker(object):
+
     def test_parametrize(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(params=["a", "b", "c"])
             def arg(request):
                 return request.param
             values = []
             def test_param(arg):
                 values.append(arg)
             def test_result():
                 assert values == list("abc")
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=4)
 
     def test_multiple_parametrization_issue_736(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(params=[1,2,3])
             def foo(request):
                 return request.param
 
             @pytest.mark.parametrize('foobar', [4,5,6])
             def test_issue(foo, foobar):
                 assert foo in [1,2,3]
                 assert foobar in [4,5,6]
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=9)
 
-    @pytest.mark.parametrize('param_args', ["'fixt, val'", "'fixt,val'", "['fixt', 'val']", "('fixt', 'val')"])
+    @pytest.mark.parametrize(
+        "param_args",
+        ["'fixt, val'", "'fixt,val'", "['fixt', 'val']", "('fixt', 'val')"],
+    )
     def test_override_parametrized_fixture_issue_979(self, testdir, param_args):
         """Make sure a parametrized argument can override a parametrized fixture.
 
         This was a regression introduced in the fix for #736.
         """
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(params=[1, 2])
             def fixt(request):
                 return request.param
 
             @pytest.mark.parametrize(%s, [(3, 'x'), (4, 'x')])
             def test_foo(fixt, val):
                 pass
-        """ % param_args)
+        """
+            % param_args
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2)
 
     def test_scope_session(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             @pytest.fixture(scope="module")
             def arg():
                 values.append(1)
                 return 1
 
             def test_1(arg):
                 assert arg == 1
             def test_2(arg):
                 assert arg == 1
                 assert len(values) == 1
             class TestClass(object):
                 def test3(self, arg):
                     assert arg == 1
                     assert len(values) == 1
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=3)
 
     def test_scope_session_exc(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             @pytest.fixture(scope="session")
             def fix():
                 values.append(1)
                 pytest.skip('skipping')
 
             def test_1(fix):
                 pass
             def test_2(fix):
                 pass
             def test_last():
                 assert values == [1]
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(skipped=2, passed=1)
 
     def test_scope_session_exc_two_fix(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             m = []
             @pytest.fixture(scope="session")
             def a():
                 values.append(1)
                 pytest.skip('skipping')
             @pytest.fixture(scope="session")
@@ -1916,17 +2235,18 @@ class TestFixtureMarker(object):
 
             def test_1(b):
                 pass
             def test_2(b):
                 pass
             def test_last():
                 assert values == [1]
                 assert m == []
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(skipped=2, passed=1)
 
     def test_scope_exc(self, testdir):
         testdir.makepyfile(
             test_foo="""
                 def test_foo(fix):
                     pass
@@ -1944,241 +2264,323 @@ class TestFixtureMarker(object):
                     pytest.skip()
                 @pytest.fixture
                 def req_list():
                     return reqs
             """,
             test_real="""
                 def test_last(req_list):
                     assert req_list == [1]
-            """
+            """,
         )
         reprec = testdir.inline_run()
         reprec.assertoutcome(skipped=2, passed=1)
 
     def test_scope_module_uses_session(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             @pytest.fixture(scope="module")
             def arg():
                 values.append(1)
                 return 1
 
             def test_1(arg):
                 assert arg == 1
             def test_2(arg):
                 assert arg == 1
                 assert len(values) == 1
             class TestClass(object):
                 def test3(self, arg):
                     assert arg == 1
                     assert len(values) == 1
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=3)
 
     def test_scope_module_and_finalizer(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             finalized_list = []
             created_list = []
             @pytest.fixture(scope="module")
             def arg(request):
                 created_list.append(1)
                 assert request.scope == "module"
                 request.addfinalizer(lambda: finalized_list.append(1))
             @pytest.fixture
             def created(request):
                 return len(created_list)
             @pytest.fixture
             def finalized(request):
                 return len(finalized_list)
-        """)
+        """
+        )
         testdir.makepyfile(
             test_mod1="""
                 def test_1(arg, created, finalized):
                     assert created == 1
                     assert finalized == 0
                 def test_2(arg, created, finalized):
                     assert created == 1
                     assert finalized == 0""",
             test_mod2="""
                 def test_3(arg, created, finalized):
                     assert created == 2
                     assert finalized == 1""",
             test_mode3="""
                 def test_4(arg, created, finalized):
                     assert created == 3
                     assert finalized == 2
-            """)
+            """,
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=4)
 
-    @pytest.mark.parametrize("method", [
-        'request.getfixturevalue("arg")',
-        'request.cached_setup(lambda: None, scope="function")',
-    ], ids=["getfixturevalue", "cached_setup"])
+    @pytest.mark.parametrize(
+        "method",
+        [
+            'request.getfixturevalue("arg")',
+            'request.cached_setup(lambda: None, scope="function")',
+        ],
+        ids=["getfixturevalue", "cached_setup"],
+    )
     def test_scope_mismatch_various(self, testdir, method):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             finalized = []
             created = []
             @pytest.fixture(scope="function")
             def arg(request):
                 pass
-        """)
+        """
+        )
         testdir.makepyfile(
             test_mod1="""
                 import pytest
                 @pytest.fixture(scope="session")
                 def arg(request):
                     %s
                 def test_1(arg):
                     pass
-            """ % method)
+            """
+            % method
+        )
         result = testdir.runpytest()
         assert result.ret != 0
-        result.stdout.fnmatch_lines([
-            "*ScopeMismatch*You tried*function*session*request*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*ScopeMismatch*You tried*function*session*request*"]
+        )
 
     def test_register_only_with_mark(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             @pytest.fixture()
             def arg():
                 return 1
-        """)
+        """
+        )
         testdir.makepyfile(
             test_mod1="""
                 import pytest
                 @pytest.fixture()
                 def arg(arg):
                     return arg + 1
                 def test_1(arg):
                     assert arg == 2
-            """)
+            """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_parametrize_and_scope(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(scope="module", params=["a", "b", "c"])
             def arg(request):
                 return request.param
             values = []
             def test_param(arg):
                 values.append(arg)
-        """)
+        """
+        )
         reprec = testdir.inline_run("-v")
         reprec.assertoutcome(passed=3)
         values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
         assert len(values) == 3
         assert "a" in values
         assert "b" in values
         assert "c" in values
 
     def test_scope_mismatch(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             @pytest.fixture(scope="function")
             def arg(request):
                 pass
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(scope="session")
             def arg(arg):
                 pass
             def test_mismatch(arg):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*ScopeMismatch*",
-            "*1 error*",
-        ])
+        result.stdout.fnmatch_lines(["*ScopeMismatch*", "*1 error*"])
 
     def test_parametrize_separated_order(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(scope="module", params=[1, 2])
             def arg(request):
                 return request.param
 
             values = []
             def test_1(arg):
                 values.append(arg)
             def test_2(arg):
                 values.append(arg)
-        """)
+        """
+        )
         reprec = testdir.inline_run("-v")
         reprec.assertoutcome(passed=4)
         values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
         assert values == [1, 1, 2, 2]
 
     def test_module_parametrized_ordering(self, testdir):
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
             console_output_style=classic
-        """)
-        testdir.makeconftest("""
+        """
+        )
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture(scope="session", params="s1 s2".split())
             def sarg():
                 pass
             @pytest.fixture(scope="module", params="m1 m2".split())
             def marg():
                 pass
-        """)
-        testdir.makepyfile(test_mod1="""
+        """
+        )
+        testdir.makepyfile(
+            test_mod1="""
             def test_func(sarg):
                 pass
             def test_func1(marg):
                 pass
-        """, test_mod2="""
+        """,
+            test_mod2="""
             def test_func2(sarg):
                 pass
             def test_func3(sarg, marg):
                 pass
             def test_func3b(sarg, marg):
                 pass
             def test_func4(marg):
                 pass
-        """)
+        """,
+        )
         result = testdir.runpytest("-v")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             test_mod1.py::test_func[s1] PASSED
             test_mod2.py::test_func2[s1] PASSED
             test_mod2.py::test_func3[s1-m1] PASSED
             test_mod2.py::test_func3b[s1-m1] PASSED
             test_mod2.py::test_func3[s1-m2] PASSED
             test_mod2.py::test_func3b[s1-m2] PASSED
             test_mod1.py::test_func[s2] PASSED
             test_mod2.py::test_func2[s2] PASSED
             test_mod2.py::test_func3[s2-m1] PASSED
             test_mod2.py::test_func3b[s2-m1] PASSED
             test_mod2.py::test_func4[m1] PASSED
             test_mod2.py::test_func3[s2-m2] PASSED
             test_mod2.py::test_func3b[s2-m2] PASSED
             test_mod2.py::test_func4[m2] PASSED
             test_mod1.py::test_func1[m1] PASSED
             test_mod1.py::test_func1[m2] PASSED
-        """)
+        """
+        )
+
+    def test_dynamic_parametrized_ordering(self, testdir):
+        testdir.makeini(
+            """
+            [pytest]
+            console_output_style=classic
+        """
+        )
+        testdir.makeconftest(
+            """
+            import pytest
+
+            def pytest_configure(config):
+                class DynamicFixturePlugin(object):
+                    @pytest.fixture(scope='session', params=['flavor1', 'flavor2'])
+                    def flavor(self, request):
+                        return request.param
+                config.pluginmanager.register(DynamicFixturePlugin(), 'flavor-fixture')
+
+            @pytest.fixture(scope='session', params=['vxlan', 'vlan'])
+            def encap(request):
+                return request.param
+
+            @pytest.fixture(scope='session', autouse='True')
+            def reprovision(request, flavor, encap):
+                pass
+        """
+        )
+        testdir.makepyfile(
+            """
+            def test(reprovision):
+                pass
+            def test2(reprovision):
+                pass
+        """
+        )
+        result = testdir.runpytest("-v")
+        result.stdout.fnmatch_lines(
+            """
+            test_dynamic_parametrized_ordering.py::test[flavor1-vxlan] PASSED
+            test_dynamic_parametrized_ordering.py::test2[flavor1-vxlan] PASSED
+            test_dynamic_parametrized_ordering.py::test[flavor2-vxlan] PASSED
+            test_dynamic_parametrized_ordering.py::test2[flavor2-vxlan] PASSED
+            test_dynamic_parametrized_ordering.py::test[flavor2-vlan] PASSED
+            test_dynamic_parametrized_ordering.py::test2[flavor2-vlan] PASSED
+            test_dynamic_parametrized_ordering.py::test[flavor1-vlan] PASSED
+            test_dynamic_parametrized_ordering.py::test2[flavor1-vlan] PASSED
+        """
+        )
 
     def test_class_ordering(self, testdir):
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
             console_output_style=classic
-        """)
-        testdir.makeconftest("""
+        """
+        )
+        testdir.makeconftest(
+            """
             import pytest
 
             values = []
 
             @pytest.fixture(scope="function", params=[1,2])
             def farg(request):
                 return request.param
 
@@ -2186,47 +2588,53 @@ class TestFixtureMarker(object):
             def carg(request):
                 return request.param
 
             @pytest.fixture(scope="function", autouse=True)
             def append(request, farg, carg):
                 def fin():
                     values.append("fin_%s%s" % (carg, farg))
                 request.addfinalizer(fin)
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             import pytest
 
             class TestClass2(object):
                 def test_1(self):
                     pass
                 def test_2(self):
                     pass
             class TestClass(object):
                 def test_3(self):
                     pass
-        """)
+        """
+        )
         result = testdir.runpytest("-vs")
-        result.stdout.fnmatch_lines("""
-            test_class_ordering.py::TestClass2::test_1[1-a] PASSED
-            test_class_ordering.py::TestClass2::test_1[2-a] PASSED
-            test_class_ordering.py::TestClass2::test_2[1-a] PASSED
-            test_class_ordering.py::TestClass2::test_2[2-a] PASSED
-            test_class_ordering.py::TestClass2::test_1[1-b] PASSED
-            test_class_ordering.py::TestClass2::test_1[2-b] PASSED
-            test_class_ordering.py::TestClass2::test_2[1-b] PASSED
-            test_class_ordering.py::TestClass2::test_2[2-b] PASSED
-            test_class_ordering.py::TestClass::test_3[1-a] PASSED
-            test_class_ordering.py::TestClass::test_3[2-a] PASSED
-            test_class_ordering.py::TestClass::test_3[1-b] PASSED
-            test_class_ordering.py::TestClass::test_3[2-b] PASSED
-        """)
+        result.stdout.re_match_lines(
+            r"""
+            test_class_ordering.py::TestClass2::test_1\[a-1\] PASSED
+            test_class_ordering.py::TestClass2::test_1\[a-2\] PASSED
+            test_class_ordering.py::TestClass2::test_2\[a-1\] PASSED
+            test_class_ordering.py::TestClass2::test_2\[a-2\] PASSED
+            test_class_ordering.py::TestClass2::test_1\[b-1\] PASSED
+            test_class_ordering.py::TestClass2::test_1\[b-2\] PASSED
+            test_class_ordering.py::TestClass2::test_2\[b-1\] PASSED
+            test_class_ordering.py::TestClass2::test_2\[b-2\] PASSED
+            test_class_ordering.py::TestClass::test_3\[a-1\] PASSED
+            test_class_ordering.py::TestClass::test_3\[a-2\] PASSED
+            test_class_ordering.py::TestClass::test_3\[b-1\] PASSED
+            test_class_ordering.py::TestClass::test_3\[b-2\] PASSED
+        """
+        )
 
     def test_parametrize_separated_order_higher_scope_first(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(scope="function", params=[1, 2])
             def arg(request):
                 param = request.param
                 request.addfinalizer(lambda: values.append("fin:%s" % param))
                 values.append("create:%s" % param)
                 return request.param
@@ -2242,35 +2650,67 @@ class TestFixtureMarker(object):
             def test_1(arg):
                 values.append("test1")
             def test_2(modarg):
                 values.append("test2")
             def test_3(arg, modarg):
                 values.append("test3")
             def test_4(modarg, arg):
                 values.append("test4")
-        """)
+        """
+        )
         reprec = testdir.inline_run("-v")
         reprec.assertoutcome(passed=12)
         values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
         expected = [
-            'create:1', 'test1', 'fin:1', 'create:2', 'test1',
-            'fin:2', 'create:mod1', 'test2', 'create:1', 'test3',
-            'fin:1', 'create:2', 'test3', 'fin:2', 'create:1',
-            'test4', 'fin:1', 'create:2', 'test4', 'fin:2',
-            'fin:mod1', 'create:mod2', 'test2', 'create:1', 'test3',
-            'fin:1', 'create:2', 'test3', 'fin:2', 'create:1',
-            'test4', 'fin:1', 'create:2', 'test4', 'fin:2',
-            'fin:mod2']
+            "create:1",
+            "test1",
+            "fin:1",
+            "create:2",
+            "test1",
+            "fin:2",
+            "create:mod1",
+            "test2",
+            "create:1",
+            "test3",
+            "fin:1",
+            "create:2",
+            "test3",
+            "fin:2",
+            "create:1",
+            "test4",
+            "fin:1",
+            "create:2",
+            "test4",
+            "fin:2",
+            "fin:mod1",
+            "create:mod2",
+            "test2",
+            "create:1",
+            "test3",
+            "fin:1",
+            "create:2",
+            "test3",
+            "fin:2",
+            "create:1",
+            "test4",
+            "fin:1",
+            "create:2",
+            "test4",
+            "fin:2",
+            "fin:mod2",
+        ]
         import pprint
+
         pprint.pprint(list(zip(values, expected)))
         assert values == expected
 
     def test_parametrized_fixture_teardown_order(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(params=[1,2], scope="class")
             def param1(request):
                 return request.param
 
             values = []
 
             class TestClass(object):
@@ -2289,53 +2729,63 @@ class TestFixtureMarker(object):
                 @classmethod
                 def teardown2(self):
                     assert values.pop() == 2
                 def test(self):
                     pass
 
             def test_finish():
                 assert not values
-        """)
+        """
+        )
         result = testdir.runpytest("-v")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *3 passed*
-        """)
+        """
+        )
         assert "error" not in result.stdout.str()
 
     def test_fixture_finalizer(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             import sys
 
             @pytest.fixture
             def browser(request):
 
                 def finalize():
                     sys.stdout.write('Finalized')
                 request.addfinalizer(finalize)
                 return {}
-        """)
+        """
+        )
         b = testdir.mkdir("subdir")
-        b.join("test_overridden_fixture_finalizer.py").write(dedent("""
+        b.join("test_overridden_fixture_finalizer.py").write(
+            dedent(
+                """
             import pytest
             @pytest.fixture
             def browser(browser):
                 browser['visited'] = True
                 return browser
 
             def test_browser(browser):
                 assert browser['visited'] is True
-        """))
+        """
+            )
+        )
         reprec = testdir.runpytest("-s")
-        for test in ['test_browser']:
-            reprec.stdout.fnmatch_lines('*Finalized*')
+        for test in ["test_browser"]:
+            reprec.stdout.fnmatch_lines("*Finalized*")
 
     def test_class_scope_with_normal_tests(self, testdir):
-        testpath = testdir.makepyfile("""
+        testpath = testdir.makepyfile(
+            """
             import pytest
 
             class Box(object):
                 value = 0
 
             @pytest.fixture(scope='class')
             def a(request):
                 Box.value += 1
@@ -2345,87 +2795,96 @@ class TestFixtureMarker(object):
                 assert a == 1
 
             class Test1(object):
                 def test_b(self, a):
                     assert a == 2
 
             class Test2(object):
                 def test_c(self, a):
-                    assert a == 3""")
+                    assert a == 3"""
+        )
         reprec = testdir.inline_run(testpath)
-        for test in ['test_a', 'test_b', 'test_c']:
+        for test in ["test_a", "test_b", "test_c"]:
             assert reprec.matchreport(test).passed
 
     def test_request_is_clean(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             @pytest.fixture(params=[1, 2])
             def fix(request):
                 request.addfinalizer(lambda: values.append(request.param))
             def test_fix(fix):
                 pass
-        """)
+        """
+        )
         reprec = testdir.inline_run("-s")
         values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
         assert values == [1, 2]
 
     def test_parametrize_separated_lifecycle(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             values = []
             @pytest.fixture(scope="module", params=[1, 2])
             def arg(request):
                 x = request.param
                 request.addfinalizer(lambda: values.append("fin%s" % x))
                 return request.param
             def test_1(arg):
                 values.append(arg)
             def test_2(arg):
                 values.append(arg)
-        """)
+        """
+        )
         reprec = testdir.inline_run("-vs")
         reprec.assertoutcome(passed=4)
         values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
         import pprint
+
         pprint.pprint(values)
         # assert len(values) == 6
         assert values[0] == values[1] == 1
         assert values[2] == "fin1"
         assert values[3] == values[4] == 2
         assert values[5] == "fin2"
 
     def test_parametrize_function_scoped_finalizers_called(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(scope="function", params=[1, 2])
             def arg(request):
                 x = request.param
                 request.addfinalizer(lambda: values.append("fin%s" % x))
                 return request.param
 
             values = []
             def test_1(arg):
                 values.append(arg)
             def test_2(arg):
                 values.append(arg)
             def test_3():
                 assert len(values) == 8
                 assert values == [1, "fin1", 2, "fin2", 1, "fin1", 2, "fin2"]
-        """)
+        """
+        )
         reprec = testdir.inline_run("-v")
         reprec.assertoutcome(passed=5)
 
     @pytest.mark.issue246
     @pytest.mark.parametrize("scope", ["session", "function", "module"])
     def test_finalizer_order_on_parametrization(self, scope, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
 
             @pytest.fixture(scope=%(scope)r, params=["1"])
             def fix1(request):
                 return request.param
 
             @pytest.fixture(scope=%(scope)r)
@@ -2442,23 +2901,26 @@ class TestFixtureMarker(object):
                 request.addfinalizer(cleanup_base)
 
             def test_begin():
                 pass
             def test_baz(base, fix2):
                 pass
             def test_other():
                 pass
-        """ % {"scope": scope})
+        """
+            % {"scope": scope}
+        )
         reprec = testdir.inline_run("-lvs")
         reprec.assertoutcome(passed=3)
 
     @pytest.mark.issue396
     def test_class_scope_parametrization_ordering(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             @pytest.fixture(params=["John", "Doe"], scope="class")
             def human(request):
                 request.addfinalizer(lambda: values.append("fin %s" % request.param))
                 return request.param
 
             class TestGreetings(object):
@@ -2466,26 +2928,40 @@ class TestFixtureMarker(object):
                     values.append("test_hello")
 
             class TestMetrics(object):
                 def test_name(self, human):
                     values.append("test_name")
 
                 def test_population(self, human):
                     values.append("test_population")
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=6)
         values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
-        assert values == ["test_hello", "fin John", "test_hello", "fin Doe",
-                          "test_name", "test_population", "fin John",
-                          "test_name", "test_population", "fin Doe"]
+        assert (
+            values
+            == [
+                "test_hello",
+                "fin John",
+                "test_hello",
+                "fin Doe",
+                "test_name",
+                "test_population",
+                "fin John",
+                "test_name",
+                "test_population",
+                "fin Doe",
+            ]
+        )
 
     def test_parametrize_setup_function(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(scope="module", params=[1, 2])
             def arg(request):
                 return request.param
 
             @pytest.fixture(scope="module", autouse=True)
             def mysetup(request, arg):
@@ -2501,70 +2977,74 @@ class TestFixtureMarker(object):
                 import pprint
                 pprint.pprint(values)
                 if arg == 1:
                     assert values == ["setup1", 1, 1, ]
                 elif arg == 2:
                     assert values == ["setup1", 1, 1, "fin1",
                                  "setup2", 2, 2, ]
 
-        """)
+        """
+        )
         reprec = testdir.inline_run("-v")
         reprec.assertoutcome(passed=6)
 
     def test_fixture_marked_function_not_collected_as_test(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture
             def test_app():
                 return 1
 
             def test_something(test_app):
                 assert test_app == 1
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_params_and_ids(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(params=[object(), object()],
                             ids=['alpha', 'beta'])
             def fix(request):
                 return request.param
 
             def test_foo(fix):
                 assert 1
-        """)
-        res = testdir.runpytest('-v')
-        res.stdout.fnmatch_lines([
-            '*test_foo*alpha*',
-            '*test_foo*beta*'])
+        """
+        )
+        res = testdir.runpytest("-v")
+        res.stdout.fnmatch_lines(["*test_foo*alpha*", "*test_foo*beta*"])
 
     def test_params_and_ids_yieldfixture(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.yield_fixture(params=[object(), object()],
                                   ids=['alpha', 'beta'])
             def fix(request):
                  yield request.param
 
             def test_foo(fix):
                 assert 1
-        """)
-        res = testdir.runpytest('-v')
-        res.stdout.fnmatch_lines([
-            '*test_foo*alpha*',
-            '*test_foo*beta*'])
+        """
+        )
+        res = testdir.runpytest("-v")
+        res.stdout.fnmatch_lines(["*test_foo*alpha*", "*test_foo*beta*"])
 
     @pytest.mark.issue920
     def test_deterministic_fixture_collection(self, testdir, monkeypatch):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(scope="module",
                             params=["A",
                                     "B",
                                     "C"])
             def A(request):
                 return request.param
@@ -2575,597 +3055,957 @@ class TestFixtureMarker(object):
                 return request.param
 
             def test_foo(B):
                 # Something funky is going on here.
                 # Despite specified seeds, on what is collected,
                 # sometimes we get unexpected passes. hashing B seems
                 # to help?
                 assert hash(B) or True
-            """)
+            """
+        )
         monkeypatch.setenv("PYTHONHASHSEED", "1")
         out1 = testdir.runpytest_subprocess("-v")
         monkeypatch.setenv("PYTHONHASHSEED", "2")
         out2 = testdir.runpytest_subprocess("-v")
-        out1 = [line for line in out1.outlines if line.startswith("test_deterministic_fixture_collection.py::test_foo")]
-        out2 = [line for line in out2.outlines if line.startswith("test_deterministic_fixture_collection.py::test_foo")]
+        out1 = [
+            line
+            for line in out1.outlines
+            if line.startswith("test_deterministic_fixture_collection.py::test_foo")
+        ]
+        out2 = [
+            line
+            for line in out2.outlines
+            if line.startswith("test_deterministic_fixture_collection.py::test_foo")
+        ]
         assert len(out1) == 12
         assert out1 == out2
 
 
 class TestRequestScopeAccess(object):
-    pytestmark = pytest.mark.parametrize(("scope", "ok", "error"), [
-        ["session", "", "fspath class function module"],
-        ["module", "module fspath", "cls function"],
-        ["class", "module fspath cls", "function"],
-        ["function", "module fspath cls function", ""]
-    ])
+    pytestmark = pytest.mark.parametrize(
+        ("scope", "ok", "error"),
+        [
+            ["session", "", "fspath class function module"],
+            ["module", "module fspath", "cls function"],
+            ["class", "module fspath cls", "function"],
+            ["function", "module fspath cls function", ""],
+        ],
+    )
 
     def test_setup(self, testdir, scope, ok, error):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(scope=%r, autouse=True)
             def myscoped(request):
                 for x in %r:
                     assert hasattr(request, x)
                 for x in %r:
                     pytest.raises(AttributeError, lambda:
                         getattr(request, x))
                 assert request.session
                 assert request.config
             def test_func():
                 pass
-        """ % (scope, ok.split(), error.split()))
+        """
+            % (scope, ok.split(), error.split())
+        )
         reprec = testdir.inline_run("-l")
         reprec.assertoutcome(passed=1)
 
     def test_funcarg(self, testdir, scope, ok, error):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(scope=%r)
             def arg(request):
                 for x in %r:
                     assert hasattr(request, x)
                 for x in %r:
                     pytest.raises(AttributeError, lambda:
                         getattr(request, x))
                 assert request.session
                 assert request.config
             def test_func(arg):
                 pass
-        """ % (scope, ok.split(), error.split()))
+        """
+            % (scope, ok.split(), error.split())
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
 
 class TestErrors(object):
+
     def test_subfactory_missing_funcarg(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture()
             def gen(qwe123):
                 return 1
             def test_something(gen):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret != 0
-        result.stdout.fnmatch_lines([
-            "*def gen(qwe123):*",
-            "*fixture*qwe123*not found*",
-            "*1 error*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*def gen(qwe123):*", "*fixture*qwe123*not found*", "*1 error*"]
+        )
 
     def test_issue498_fixture_finalizer_failing(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture
             def fix1(request):
                 def f():
                     raise KeyError
                 request.addfinalizer(f)
                 return object()
 
             values = []
             def test_1(fix1):
                 values.append(fix1)
             def test_2(fix1):
                 values.append(fix1)
             def test_3():
                 assert values[0] != values[1]
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *ERROR*teardown*test_1*
             *KeyError*
             *ERROR*teardown*test_2*
             *KeyError*
             *3 pass*2 error*
-        """)
+        """
+        )
 
     def test_setupfunc_missing_funcarg(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(autouse=True)
             def gen(qwe123):
                 return 1
             def test_something():
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret != 0
-        result.stdout.fnmatch_lines([
-            "*def gen(qwe123):*",
-            "*fixture*qwe123*not found*",
-            "*1 error*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*def gen(qwe123):*", "*fixture*qwe123*not found*", "*1 error*"]
+        )
 
 
 class TestShowFixtures(object):
+
     def test_funcarg_compat(self, testdir):
         config = testdir.parseconfigure("--funcargs")
         assert config.option.showfixtures
 
     def test_show_fixtures(self, testdir):
         result = testdir.runpytest("--fixtures")
-        result.stdout.fnmatch_lines([
-            "*tmpdir*",
-            "*temporary directory*",
-        ])
+        result.stdout.fnmatch_lines(["*tmpdir*", "*temporary directory*"])
 
     def test_show_fixtures_verbose(self, testdir):
         result = testdir.runpytest("--fixtures", "-v")
-        result.stdout.fnmatch_lines([
-            "*tmpdir*--*tmpdir.py*",
-            "*temporary directory*",
-        ])
+        result.stdout.fnmatch_lines(["*tmpdir*--*tmpdir.py*", "*temporary directory*"])
 
     def test_show_fixtures_testmodule(self, testdir):
-        p = testdir.makepyfile('''
+        p = testdir.makepyfile(
+            '''
             import pytest
             @pytest.fixture
             def _arg0():
                 """ hidden """
             @pytest.fixture
             def arg1():
                 """  hello world """
-        ''')
+        '''
+        )
         result = testdir.runpytest("--fixtures", p)
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *tmpdir
             *fixtures defined from*
             *arg1*
             *hello world*
-        """)
+        """
+        )
         assert "arg0" not in result.stdout.str()
 
     @pytest.mark.parametrize("testmod", [True, False])
     def test_show_fixtures_conftest(self, testdir, testmod):
-        testdir.makeconftest('''
+        testdir.makeconftest(
+            '''
             import pytest
             @pytest.fixture
             def arg1():
                 """  hello world """
-        ''')
+        '''
+        )
         if testmod:
-            testdir.makepyfile("""
+            testdir.makepyfile(
+                """
                 def test_hello():
                     pass
-            """)
+            """
+            )
         result = testdir.runpytest("--fixtures")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *tmpdir*
             *fixtures defined from*conftest*
             *arg1*
             *hello world*
-        """)
+        """
+        )
 
     def test_show_fixtures_trimmed_doc(self, testdir):
-        p = testdir.makepyfile(dedent('''
+        p = testdir.makepyfile(
+            dedent(
+                '''
             import pytest
             @pytest.fixture
             def arg1():
                 """
                 line1
                 line2
 
                 """
             @pytest.fixture
             def arg2():
                 """
                 line1
                 line2
 
                 """
-        '''))
+        '''
+            )
+        )
         result = testdir.runpytest("--fixtures", p)
-        result.stdout.fnmatch_lines(dedent("""
+        result.stdout.fnmatch_lines(
+            dedent(
+                """
             * fixtures defined from test_show_fixtures_trimmed_doc *
             arg2
                 line1
                 line2
             arg1
                 line1
                 line2
 
-        """))
+        """
+            )
+        )
 
     def test_show_fixtures_indented_doc(self, testdir):
-        p = testdir.makepyfile(dedent('''
+        p = testdir.makepyfile(
+            dedent(
+                '''
             import pytest
             @pytest.fixture
             def fixture1():
                 """
                 line1
                     indented line
                 """
-        '''))
+        '''
+            )
+        )
         result = testdir.runpytest("--fixtures", p)
-        result.stdout.fnmatch_lines(dedent("""
+        result.stdout.fnmatch_lines(
+            dedent(
+                """
             * fixtures defined from test_show_fixtures_indented_doc *
             fixture1
                 line1
                     indented line
-        """))
+        """
+            )
+        )
 
     def test_show_fixtures_indented_doc_first_line_unindented(self, testdir):
-        p = testdir.makepyfile(dedent('''
+        p = testdir.makepyfile(
+            dedent(
+                '''
             import pytest
             @pytest.fixture
             def fixture1():
                 """line1
                 line2
                     indented line
                 """
-        '''))
+        '''
+            )
+        )
         result = testdir.runpytest("--fixtures", p)
-        result.stdout.fnmatch_lines(dedent("""
+        result.stdout.fnmatch_lines(
+            dedent(
+                """
             * fixtures defined from test_show_fixtures_indented_doc_first_line_unindented *
             fixture1
                 line1
                 line2
                     indented line
-        """))
+        """
+            )
+        )
 
     def test_show_fixtures_indented_in_class(self, testdir):
-        p = testdir.makepyfile(dedent('''
+        p = testdir.makepyfile(
+            dedent(
+                '''
             import pytest
-            class TestClass:
+            class TestClass(object):
                 @pytest.fixture
                 def fixture1(self):
                     """line1
                     line2
                         indented line
                     """
-        '''))
+        '''
+            )
+        )
         result = testdir.runpytest("--fixtures", p)
-        result.stdout.fnmatch_lines(dedent("""
+        result.stdout.fnmatch_lines(
+            dedent(
+                """
             * fixtures defined from test_show_fixtures_indented_in_class *
             fixture1
                 line1
                 line2
                     indented line
-        """))
+        """
+            )
+        )
 
     def test_show_fixtures_different_files(self, testdir):
         """
         #833: --fixtures only shows fixtures from first file
         """
-        testdir.makepyfile(test_a='''
+        testdir.makepyfile(
+            test_a='''
             import pytest
 
             @pytest.fixture
             def fix_a():
                 """Fixture A"""
                 pass
 
             def test_a(fix_a):
                 pass
-        ''')
-        testdir.makepyfile(test_b='''
+        '''
+        )
+        testdir.makepyfile(
+            test_b='''
             import pytest
 
             @pytest.fixture
             def fix_b():
                 """Fixture B"""
                 pass
 
             def test_b(fix_b):
                 pass
-        ''')
+        '''
+        )
         result = testdir.runpytest("--fixtures")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             * fixtures defined from test_a *
             fix_a
                 Fixture A
 
             * fixtures defined from test_b *
             fix_b
                 Fixture B
-        """)
+        """
+        )
 
     def test_show_fixtures_with_same_name(self, testdir):
-        testdir.makeconftest('''
+        testdir.makeconftest(
+            '''
             import pytest
             @pytest.fixture
             def arg1():
                 """Hello World in conftest.py"""
                 return "Hello World"
-        ''')
-        testdir.makepyfile('''
+        '''
+        )
+        testdir.makepyfile(
+            """
             def test_foo(arg1):
                 assert arg1 == "Hello World"
-        ''')
-        testdir.makepyfile('''
+        """
+        )
+        testdir.makepyfile(
+            '''
             import pytest
             @pytest.fixture
             def arg1():
                 """Hi from test module"""
                 return "Hi"
             def test_bar(arg1):
                 assert arg1 == "Hi"
-        ''')
+        '''
+        )
         result = testdir.runpytest("--fixtures")
-        result.stdout.fnmatch_lines('''
+        result.stdout.fnmatch_lines(
+            """
             * fixtures defined from conftest *
             arg1
                 Hello World in conftest.py
 
             * fixtures defined from test_show_fixtures_with_same_name *
             arg1
                 Hi from test module
-        ''')
-
-
-@pytest.mark.parametrize('flavor', ['fixture', 'yield_fixture'])
+        """
+        )
+
+    def test_fixture_disallow_twice(self):
+        """Test that applying @pytest.fixture twice generates an error (#2334)."""
+        with pytest.raises(ValueError):
+
+            @pytest.fixture
+            @pytest.fixture
+            def foo():
+                pass
+
+
+@pytest.mark.parametrize("flavor", ["fixture", "yield_fixture"])
 class TestContextManagerFixtureFuncs(object):
 
     def test_simple(self, testdir, flavor):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.{flavor}
             def arg1():
                 print ("setup")
                 yield 1
                 print ("teardown")
             def test_1(arg1):
                 print ("test1 %s" % arg1)
             def test_2(arg1):
                 print ("test2 %s" % arg1)
                 assert 0
-        """.format(flavor=flavor))
+        """.format(
+                flavor=flavor
+            )
+        )
         result = testdir.runpytest("-s")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *setup*
             *test1 1*
             *teardown*
             *setup*
             *test2 1*
             *teardown*
-        """)
+        """
+        )
 
     def test_scoped(self, testdir, flavor):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.{flavor}(scope="module")
             def arg1():
                 print ("setup")
                 yield 1
                 print ("teardown")
             def test_1(arg1):
                 print ("test1 %s" % arg1)
             def test_2(arg1):
                 print ("test2 %s" % arg1)
-        """.format(flavor=flavor))
+        """.format(
+                flavor=flavor
+            )
+        )
         result = testdir.runpytest("-s")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *setup*
             *test1 1*
             *test2 1*
             *teardown*
-        """)
+        """
+        )
 
     def test_setup_exception(self, testdir, flavor):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.{flavor}(scope="module")
             def arg1():
                 pytest.fail("setup")
                 yield 1
             def test_1(arg1):
                 pass
-        """.format(flavor=flavor))
+        """.format(
+                flavor=flavor
+            )
+        )
         result = testdir.runpytest("-s")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *pytest.fail*setup*
             *1 error*
-        """)
+        """
+        )
 
     def test_teardown_exception(self, testdir, flavor):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.{flavor}(scope="module")
             def arg1():
                 yield 1
                 pytest.fail("teardown")
             def test_1(arg1):
                 pass
-        """.format(flavor=flavor))
+        """.format(
+                flavor=flavor
+            )
+        )
         result = testdir.runpytest("-s")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *pytest.fail*teardown*
             *1 passed*1 error*
-        """)
+        """
+        )
 
     def test_yields_more_than_one(self, testdir, flavor):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.{flavor}(scope="module")
             def arg1():
                 yield 1
                 yield 2
             def test_1(arg1):
                 pass
-        """.format(flavor=flavor))
+        """.format(
+                flavor=flavor
+            )
+        )
         result = testdir.runpytest("-s")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *fixture function*
             *test_yields*:2*
-        """)
+        """
+        )
 
     def test_custom_name(self, testdir, flavor):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.{flavor}(name='meow')
             def arg1():
                 return 'mew'
             def test_1(meow):
                 print(meow)
-        """.format(flavor=flavor))
+        """.format(
+                flavor=flavor
+            )
+        )
         result = testdir.runpytest("-s")
         result.stdout.fnmatch_lines("*mew*")
 
 
 class TestParameterizedSubRequest(object):
+
     def test_call_from_fixture(self, testdir):
-        testfile = testdir.makepyfile("""
+        testfile = testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(params=[0, 1, 2])
             def fix_with_param(request):
                 return request.param
 
             @pytest.fixture
             def get_named_fixture(request):
                 return request.getfixturevalue('fix_with_param')
 
             def test_foo(request, get_named_fixture):
                 pass
-            """)
+            """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             E*Failed: The requested fixture has no parameter defined for the current test.
             E*
             E*Requested fixture 'fix_with_param' defined in:
-            E*{0}:4
+            E*{}:4
             E*Requested here:
-            E*{1}:9
+            E*{}:9
             *1 error*
-            """.format(testfile.basename, testfile.basename))
+            """.format(
+                testfile.basename, testfile.basename
+            )
+        )
 
     def test_call_from_test(self, testdir):
-        testfile = testdir.makepyfile("""
+        testfile = testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(params=[0, 1, 2])
             def fix_with_param(request):
                 return request.param
 
             def test_foo(request):
                 request.getfixturevalue('fix_with_param')
-            """)
+            """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             E*Failed: The requested fixture has no parameter defined for the current test.
             E*
             E*Requested fixture 'fix_with_param' defined in:
-            E*{0}:4
+            E*{}:4
             E*Requested here:
-            E*{1}:8
+            E*{}:8
             *1 failed*
-            """.format(testfile.basename, testfile.basename))
+            """.format(
+                testfile.basename, testfile.basename
+            )
+        )
 
     def test_external_fixture(self, testdir):
-        conffile = testdir.makeconftest("""
+        conffile = testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture(params=[0, 1, 2])
             def fix_with_param(request):
                 return request.param
-            """)
-
-        testfile = testdir.makepyfile("""
+            """
+        )
+
+        testfile = testdir.makepyfile(
+            """
             def test_foo(request):
                 request.getfixturevalue('fix_with_param')
-            """)
+            """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             E*Failed: The requested fixture has no parameter defined for the current test.
             E*
             E*Requested fixture 'fix_with_param' defined in:
-            E*{0}:4
+            E*{}:4
             E*Requested here:
-            E*{1}:2
+            E*{}:2
             *1 failed*
-            """.format(conffile.basename, testfile.basename))
+            """.format(
+                conffile.basename, testfile.basename
+            )
+        )
 
     def test_non_relative_path(self, testdir):
-        tests_dir = testdir.mkdir('tests')
-        fixdir = testdir.mkdir('fixtures')
+        tests_dir = testdir.mkdir("tests")
+        fixdir = testdir.mkdir("fixtures")
         fixfile = fixdir.join("fix.py")
-        fixfile.write(_pytest._code.Source("""
+        fixfile.write(
+            _pytest._code.Source(
+                """
             import pytest
 
             @pytest.fixture(params=[0, 1, 2])
             def fix_with_param(request):
                 return request.param
-            """))
+            """
+            )
+        )
 
         testfile = tests_dir.join("test_foos.py")
-        testfile.write(_pytest._code.Source("""
+        testfile.write(
+            _pytest._code.Source(
+                """
             from fix import fix_with_param
 
             def test_foo(request):
                 request.getfixturevalue('fix_with_param')
-            """))
+            """
+            )
+        )
 
         tests_dir.chdir()
         testdir.syspathinsert(fixdir)
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             E*Failed: The requested fixture has no parameter defined for the current test.
             E*
             E*Requested fixture 'fix_with_param' defined in:
-            E*{0}:5
+            E*{}:5
             E*Requested here:
-            E*{1}:5
+            E*{}:5
             *1 failed*
-            """.format(fixfile.strpath, testfile.basename))
+            """.format(
+                fixfile.strpath, testfile.basename
+            )
+        )
 
 
 def test_pytest_fixture_setup_and_post_finalizer_hook(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         from __future__ import print_function
         def pytest_fixture_setup(fixturedef, request):
             print('ROOT setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
         def pytest_fixture_post_finalizer(fixturedef, request):
             print('ROOT finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
-    """)
-    testdir.makepyfile(**{
-        'tests/conftest.py': """
+    """
+    )
+    testdir.makepyfile(
+        **{
+            "tests/conftest.py": """
             from __future__ import print_function
             def pytest_fixture_setup(fixturedef, request):
                 print('TESTS setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
             def pytest_fixture_post_finalizer(fixturedef, request):
                 print('TESTS finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
         """,
-        'tests/test_hooks.py': """
+            "tests/test_hooks.py": """
             from __future__ import print_function
             import pytest
 
             @pytest.fixture()
             def my_fixture():
                 return 'some'
 
             def test_func(my_fixture):
                 print('TEST test_func')
                 assert my_fixture == 'some'
-        """
-    })
+        """,
+        }
+    )
     result = testdir.runpytest("-s")
     assert result.ret == 0
-    result.stdout.fnmatch_lines([
-        "*TESTS setup hook called for my_fixture from test_func*",
-        "*ROOT setup hook called for my_fixture from test_func*",
-        "*TEST test_func*",
-        "*TESTS finalizer hook called for my_fixture from test_func*",
-        "*ROOT finalizer hook called for my_fixture from test_func*",
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*TESTS setup hook called for my_fixture from test_func*",
+            "*ROOT setup hook called for my_fixture from test_func*",
+            "*TEST test_func*",
+            "*TESTS finalizer hook called for my_fixture from test_func*",
+            "*ROOT finalizer hook called for my_fixture from test_func*",
+        ]
+    )
+
+
+class TestScopeOrdering(object):
+    """Class of tests that ensure fixtures are ordered based on their scopes (#2405)"""
+
+    @pytest.mark.parametrize("use_mark", [True, False])
+    def test_func_closure_module_auto(self, testdir, use_mark):
+        """Semantically identical to the example posted in #2405 when ``use_mark=True``"""
+        testdir.makepyfile(
+            """
+            import pytest
+
+            @pytest.fixture(scope='module', autouse={autouse})
+            def m1(): pass
+
+            if {use_mark}:
+                pytestmark = pytest.mark.usefixtures('m1')
+
+            @pytest.fixture(scope='function', autouse=True)
+            def f1(): pass
+
+            def test_func(m1):
+                pass
+        """.format(
+                autouse=not use_mark, use_mark=use_mark
+            )
+        )
+        items, _ = testdir.inline_genitems()
+        request = FixtureRequest(items[0])
+        assert request.fixturenames == "m1 f1".split()
+
+    def test_func_closure_with_native_fixtures(self, testdir, monkeypatch):
+        """Sanity check that verifies the order returned by the closures and the actual fixture execution order:
+        The execution order may differ because of fixture inter-dependencies.
+        """
+        monkeypatch.setattr(pytest, "FIXTURE_ORDER", [], raising=False)
+        testdir.makepyfile(
+            """
+            import pytest
+
+            FIXTURE_ORDER = pytest.FIXTURE_ORDER
+
+            @pytest.fixture(scope="session")
+            def s1():
+                FIXTURE_ORDER.append('s1')
+
+            @pytest.fixture(scope="module")
+            def m1():
+                FIXTURE_ORDER.append('m1')
+
+            @pytest.fixture(scope='session')
+            def my_tmpdir_factory():
+                FIXTURE_ORDER.append('my_tmpdir_factory')
+
+            @pytest.fixture
+            def my_tmpdir(my_tmpdir_factory):
+                FIXTURE_ORDER.append('my_tmpdir')
+
+            @pytest.fixture
+            def f1(my_tmpdir):
+                FIXTURE_ORDER.append('f1')
+
+            @pytest.fixture
+            def f2():
+                FIXTURE_ORDER.append('f2')
+
+            def test_foo(f1, m1, f2, s1): pass
+        """
+        )
+        items, _ = testdir.inline_genitems()
+        request = FixtureRequest(items[0])
+        # order of fixtures based on their scope and position in the parameter list
+        assert request.fixturenames == "s1 my_tmpdir_factory m1 f1 f2 my_tmpdir".split()
+        testdir.runpytest()
+        # actual fixture execution differs: dependent fixtures must be created first ("my_tmpdir")
+        assert pytest.FIXTURE_ORDER == "s1 my_tmpdir_factory m1 my_tmpdir f1 f2".split()
+
+    def test_func_closure_module(self, testdir):
+        testdir.makepyfile(
+            """
+            import pytest
+
+            @pytest.fixture(scope='module')
+            def m1(): pass
+
+            @pytest.fixture(scope='function')
+            def f1(): pass
+
+            def test_func(f1, m1):
+                pass
+        """
+        )
+        items, _ = testdir.inline_genitems()
+        request = FixtureRequest(items[0])
+        assert request.fixturenames == "m1 f1".split()
+
+    def test_func_closure_scopes_reordered(self, testdir):
+        """Test ensures that fixtures are ordered by scope regardless of the order of the parameters, although
+        fixtures of same scope keep the declared order
+        """
+        testdir.makepyfile(
+            """
+            import pytest
+
+            @pytest.fixture(scope='session')
+            def s1(): pass
+
+            @pytest.fixture(scope='module')
+            def m1(): pass
+
+            @pytest.fixture(scope='function')
+            def f1(): pass
+
+            @pytest.fixture(scope='function')
+            def f2(): pass
+
+            class Test:
+
+                @pytest.fixture(scope='class')
+                def c1(cls): pass
+
+                def test_func(self, f2, f1, c1, m1, s1):
+                    pass
+        """
+        )
+        items, _ = testdir.inline_genitems()
+        request = FixtureRequest(items[0])
+        assert request.fixturenames == "s1 m1 c1 f2 f1".split()
+
+    def test_func_closure_same_scope_closer_root_first(self, testdir):
+        """Auto-use fixtures of same scope are ordered by closer-to-root first"""
+        testdir.makeconftest(
+            """
+            import pytest
+
+            @pytest.fixture(scope='module', autouse=True)
+            def m_conf(): pass
+        """
+        )
+        testdir.makepyfile(
+            **{
+                "sub/conftest.py": """
+                import pytest
+
+                @pytest.fixture(scope='module', autouse=True)
+                def m_sub(): pass
+            """,
+                "sub/test_func.py": """
+                import pytest
+
+                @pytest.fixture(scope='module', autouse=True)
+                def m_test(): pass
+
+                @pytest.fixture(scope='function')
+                def f1(): pass
+
+                def test_func(m_test, f1):
+                    pass
+        """,
+            }
+        )
+        items, _ = testdir.inline_genitems()
+        request = FixtureRequest(items[0])
+        assert request.fixturenames == "m_conf m_sub m_test f1".split()
+
+    def test_func_closure_all_scopes_complex(self, testdir):
+        """Complex test involving all scopes and mixing autouse with normal fixtures"""
+        testdir.makeconftest(
+            """
+            import pytest
+
+            @pytest.fixture(scope='session')
+            def s1(): pass
+        """
+        )
+        testdir.makepyfile(
+            """
+            import pytest
+
+            @pytest.fixture(scope='module', autouse=True)
+            def m1(): pass
+
+            @pytest.fixture(scope='module')
+            def m2(s1): pass
+
+            @pytest.fixture(scope='function')
+            def f1(): pass
+
+            @pytest.fixture(scope='function')
+            def f2(): pass
+
+            class Test:
+
+                @pytest.fixture(scope='class', autouse=True)
+                def c1(self):
+                    pass
+
+                def test_func(self, f2, f1, m2):
+                    pass
+        """
+        )
+        items, _ = testdir.inline_genitems()
+        request = FixtureRequest(items[0])
+        assert request.fixturenames == "s1 m1 m2 c1 f2 f1".split()
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/python/integration.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/python/integration.py
@@ -1,88 +1,100 @@
 import pytest
 from _pytest import python
 from _pytest import runner
 
 
 class TestOEJSKITSpecials(object):
+
     def test_funcarg_non_pycollectobj(self, testdir):  # rough jstests usage
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             def pytest_pycollect_makeitem(collector, name, obj):
                 if name == "MyClass":
                     return MyCollector(name, parent=collector)
             class MyCollector(pytest.Collector):
                 def reportinfo(self):
                     return self.fspath, 3, "xyz"
-        """)
-        modcol = testdir.getmodulecol("""
+        """
+        )
+        modcol = testdir.getmodulecol(
+            """
             import pytest
             @pytest.fixture
             def arg1(request):
                 return 42
             class MyClass(object):
                 pass
-        """)
+        """
+        )
         # this hook finds funcarg factories
         rep = runner.collect_one_node(collector=modcol)
         clscol = rep.result[0]
         clscol.obj = lambda arg1: None
         clscol.funcargs = {}
         pytest._fillfuncargs(clscol)
-        assert clscol.funcargs['arg1'] == 42
+        assert clscol.funcargs["arg1"] == 42
 
     def test_autouse_fixture(self, testdir):  # rough jstests usage
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             def pytest_pycollect_makeitem(collector, name, obj):
                 if name == "MyClass":
                     return MyCollector(name, parent=collector)
             class MyCollector(pytest.Collector):
                 def reportinfo(self):
                     return self.fspath, 3, "xyz"
-        """)
-        modcol = testdir.getmodulecol("""
+        """
+        )
+        modcol = testdir.getmodulecol(
+            """
             import pytest
             @pytest.fixture(autouse=True)
             def hello():
                 pass
             @pytest.fixture
             def arg1(request):
                 return 42
             class MyClass(object):
                 pass
-        """)
+        """
+        )
         # this hook finds funcarg factories
         rep = runner.collect_one_node(modcol)
         clscol = rep.result[0]
         clscol.obj = lambda: None
         clscol.funcargs = {}
         pytest._fillfuncargs(clscol)
         assert not clscol.funcargs
 
 
 def test_wrapped_getfslineno():
+
     def func():
         pass
 
     def wrap(f):
         func.__wrapped__ = f
         func.patchings = ["qwe"]
         return func
 
     @wrap
     def wrapped_func(x, y, z):
         pass
+
     fs, lineno = python.getfslineno(wrapped_func)
     fs2, lineno2 = python.getfslineno(wrap)
     assert lineno > lineno2, "getfslineno does not unwrap correctly"
 
 
 class TestMockDecoration(object):
+
     def test_wrapped_getfuncargnames(self):
         from _pytest.compat import getfuncargnames
 
         def wrap(f):
 
             def func():
                 pass
 
@@ -91,70 +103,104 @@ class TestMockDecoration(object):
 
         @wrap
         def f(x):
             pass
 
         values = getfuncargnames(f)
         assert values == ("x",)
 
+    @pytest.mark.xfail(
+        strict=False, reason="getfuncargnames breaks if mock is imported"
+    )
     def test_wrapped_getfuncargnames_patching(self):
         from _pytest.compat import getfuncargnames
 
         def wrap(f):
+
             def func():
                 pass
+
             func.__wrapped__ = f
             func.patchings = ["qwe"]
             return func
 
         @wrap
         def f(x, y, z):
             pass
 
         values = getfuncargnames(f)
         assert values == ("y", "z")
 
     def test_unittest_mock(self, testdir):
         pytest.importorskip("unittest.mock")
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import unittest.mock
             class T(unittest.TestCase):
                 @unittest.mock.patch("os.path.abspath")
                 def test_hello(self, abspath):
                     import os
                     os.path.abspath("hello")
                     abspath.assert_any_call("hello")
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_unittest_mock_and_fixture(self, testdir):
         pytest.importorskip("unittest.mock")
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import os.path
             import unittest.mock
             import pytest
 
             @pytest.fixture
             def inject_me():
                 pass
 
             @unittest.mock.patch.object(os.path, "abspath",
                                         new=unittest.mock.MagicMock)
             def test_hello(inject_me):
                 import os
                 os.path.abspath("hello")
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
+    def test_unittest_mock_and_pypi_mock(self, testdir):
+        pytest.importorskip("unittest.mock")
+        pytest.importorskip("mock", "1.0.1")
+        testdir.makepyfile(
+            """
+            import mock
+            import unittest.mock
+            class TestBoth(object):
+                @unittest.mock.patch("os.path.abspath")
+                def test_hello(self, abspath):
+                    import os
+                    os.path.abspath("hello")
+                    abspath.assert_any_call("hello")
+
+                @mock.patch("os.path.abspath")
+                def test_hello_mock(self, abspath):
+                    import os
+                    os.path.abspath("hello")
+                    abspath.assert_any_call("hello")
+        """
+        )
+        reprec = testdir.inline_run()
+        reprec.assertoutcome(passed=2)
+
     def test_mock(self, testdir):
         pytest.importorskip("mock", "1.0.1")
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import os
             import unittest
             import mock
 
             class T(unittest.TestCase):
                 @mock.patch("os.path.abspath")
                 def test_hello(self, abspath):
                     os.path.abspath("hello")
@@ -164,203 +210,228 @@ class TestMockDecoration(object):
             @mock.patch("os.path.abspath")
             @mock.patch("os.path.normpath")
             @mock.patch("os.path.basename", new=mock_basename)
             def test_someting(normpath, abspath, tmpdir):
                 abspath.return_value = "this"
                 os.path.normpath(os.path.abspath("hello"))
                 normpath.assert_any_call("this")
                 assert os.path.basename("123") == "mock_basename"
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2)
         calls = reprec.getcalls("pytest_runtest_logreport")
-        funcnames = [call.report.location[2] for call in calls
-                     if call.report.when == "call"]
+        funcnames = [
+            call.report.location[2] for call in calls if call.report.when == "call"
+        ]
         assert funcnames == ["T.test_hello", "test_someting"]
 
     def test_mock_sorting(self, testdir):
         pytest.importorskip("mock", "1.0.1")
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import os
             import mock
 
             @mock.patch("os.path.abspath")
             def test_one(abspath):
                 pass
             @mock.patch("os.path.abspath")
             def test_two(abspath):
                 pass
             @mock.patch("os.path.abspath")
             def test_three(abspath):
                 pass
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         calls = reprec.getreports("pytest_runtest_logreport")
         calls = [x for x in calls if x.when == "call"]
         names = [x.nodeid.split("::")[-1] for x in calls]
         assert names == ["test_one", "test_two", "test_three"]
 
     def test_mock_double_patch_issue473(self, testdir):
         pytest.importorskip("mock", "1.0.1")
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             from mock import patch
             from pytest import mark
 
             @patch('os.getcwd')
             @patch('os.path')
             @mark.slow
             class TestSimple(object):
                 def test_simple_thing(self, mock_path, mock_getcwd):
                     pass
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
 
 class TestReRunTests(object):
+
     def test_rerun(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             from _pytest.runner import runtestprotocol
             def pytest_runtest_protocol(item, nextitem):
                 runtestprotocol(item, log=False, nextitem=nextitem)
                 runtestprotocol(item, log=True, nextitem=nextitem)
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             import pytest
             count = 0
             req = None
             @pytest.fixture
             def fix(request):
                 global count, req
                 assert request != req
                 req = request
                 print ("fix count %s" % count)
                 count += 1
             def test_fix(fix):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest("-s")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *fix count 0*
             *fix count 1*
-        """)
-        result.stdout.fnmatch_lines("""
+        """
+        )
+        result.stdout.fnmatch_lines(
+            """
             *2 passed*
-        """)
+        """
+        )
 
 
 def test_pytestconfig_is_session_scoped():
     from _pytest.fixtures import pytestconfig
+
     assert pytestconfig._pytestfixturefunction.scope == "session"
 
 
 class TestNoselikeTestAttribute(object):
+
     def test_module_with_global_test(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             __test__ = False
             def test_hello():
                 pass
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         assert not reprec.getfailedcollections()
         calls = reprec.getreports("pytest_runtest_logreport")
         assert not calls
 
     def test_class_and_method(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             __test__ = True
             def test_func():
                 pass
             test_func.__test__ = False
 
             class TestSome(object):
                 __test__ = False
                 def test_method(self):
                     pass
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         assert not reprec.getfailedcollections()
         calls = reprec.getreports("pytest_runtest_logreport")
         assert not calls
 
     def test_unittest_class(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import unittest
             class TC(unittest.TestCase):
                 def test_1(self):
                     pass
             class TC2(unittest.TestCase):
                 __test__ = False
                 def test_2(self):
                     pass
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         assert not reprec.getfailedcollections()
         call = reprec.getcalls("pytest_collection_modifyitems")[0]
         assert len(call.items) == 1
         assert call.items[0].cls.__name__ == "TC"
 
     def test_class_with_nasty_getattr(self, testdir):
         """Make sure we handle classes with a custom nasty __getattr__ right.
 
         With a custom __getattr__ which e.g. returns a function (like with a
         RPC wrapper), we shouldn't assume this meant "__test__ = True".
         """
         # https://github.com/pytest-dev/pytest/issues/1204
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             class MetaModel(type):
 
                 def __getattr__(cls, key):
                     return lambda: None
 
 
             BaseModel = MetaModel('Model', (), {})
 
 
             class Model(BaseModel):
 
                 __metaclass__ = MetaModel
 
                 def test_blah(self):
                     pass
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         assert not reprec.getfailedcollections()
         call = reprec.getcalls("pytest_collection_modifyitems")[0]
         assert not call.items
 
 
 @pytest.mark.issue351
 class TestParameterize(object):
 
     def test_idfn_marker(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             def idfn(param):
                 if param == 0:
                     return 'spam'
                 elif param == 1:
                     return 'ham'
                 else:
                     return None
 
             @pytest.mark.parametrize('a,b', [(0, 2), (1, 2)], ids=idfn)
             def test_params(a, b):
                 pass
-        """)
-        res = testdir.runpytest('--collect-only')
-        res.stdout.fnmatch_lines([
-            "*spam-2*",
-            "*ham-2*",
-        ])
+        """
+        )
+        res = testdir.runpytest("--collect-only")
+        res.stdout.fnmatch_lines(["*spam-2*", "*ham-2*"])
 
     def test_idfn_fixture(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             def idfn(param):
                 if param == 0:
                     return 'spam'
                 elif param == 1:
                     return 'ham'
                 else:
@@ -371,14 +442,12 @@ class TestParameterize(object):
                 return request.param
 
             @pytest.fixture(params=[1, 2], ids=idfn)
             def b(request):
                 return request.param
 
             def test_params(a, b):
                 pass
-        """)
-        res = testdir.runpytest('--collect-only')
-        res.stdout.fnmatch_lines([
-            "*spam-2*",
-            "*ham-2*",
-        ])
+        """
+        )
+        res = testdir.runpytest("--collect-only")
+        res.stdout.fnmatch_lines(["*spam-2*", "*ham-2*"])
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/python/metafunc.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/python/metafunc.py
@@ -1,628 +1,748 @@
 # -*- coding: utf-8 -*-
 import re
 import sys
-
+import attr
 import _pytest._code
 import py
 import pytest
 from _pytest import python, fixtures
 
 import hypothesis
 from hypothesis import strategies
 
 PY3 = sys.version_info >= (3, 0)
 
 
 class TestMetafunc(object):
-    def Metafunc(self, func):
+
+    def Metafunc(self, func, config=None):
         # the unit tests of this class check if things work correctly
         # on the funcarg level, so we don't need a full blown
         # initiliazation
         class FixtureInfo(object):
             name2fixturedefs = None
 
             def __init__(self, names):
                 self.names_closure = names
 
+        @attr.s
+        class DefinitionMock(object):
+            obj = attr.ib()
+
         names = fixtures.getfuncargnames(func)
         fixtureinfo = FixtureInfo(names)
-        return python.Metafunc(func, fixtureinfo, None)
+        definition = DefinitionMock(func)
+        return python.Metafunc(definition, fixtureinfo, config)
 
     def test_no_funcargs(self, testdir):
+
         def function():
             pass
+
         metafunc = self.Metafunc(function)
         assert not metafunc.fixturenames
         repr(metafunc._calls)
 
     def test_function_basic(self):
+
         def func(arg1, arg2="qwe"):
             pass
+
         metafunc = self.Metafunc(func)
         assert len(metafunc.fixturenames) == 1
-        assert 'arg1' in metafunc.fixturenames
+        assert "arg1" in metafunc.fixturenames
         assert metafunc.function is func
         assert metafunc.cls is None
 
     def test_addcall_no_args(self):
+
         def func(arg1):
             pass
+
         metafunc = self.Metafunc(func)
         metafunc.addcall()
         assert len(metafunc._calls) == 1
         call = metafunc._calls[0]
         assert call.id == "0"
-        assert not hasattr(call, 'param')
+        assert not hasattr(call, "param")
 
     def test_addcall_id(self):
+
         def func(arg1):
             pass
+
         metafunc = self.Metafunc(func)
         pytest.raises(ValueError, "metafunc.addcall(id=None)")
 
         metafunc.addcall(id=1)
         pytest.raises(ValueError, "metafunc.addcall(id=1)")
         pytest.raises(ValueError, "metafunc.addcall(id='1')")
         metafunc.addcall(id=2)
         assert len(metafunc._calls) == 2
         assert metafunc._calls[0].id == "1"
         assert metafunc._calls[1].id == "2"
 
     def test_addcall_param(self):
+
         def func(arg1):
             pass
+
         metafunc = self.Metafunc(func)
 
         class obj(object):
             pass
 
         metafunc.addcall(param=obj)
         metafunc.addcall(param=obj)
         metafunc.addcall(param=1)
         assert len(metafunc._calls) == 3
         assert metafunc._calls[0].getparam("arg1") == obj
         assert metafunc._calls[1].getparam("arg1") == obj
         assert metafunc._calls[2].getparam("arg1") == 1
 
     def test_addcall_funcargs(self):
+
         def func(x):
             pass
 
         metafunc = self.Metafunc(func)
 
         class obj(object):
             pass
 
         metafunc.addcall(funcargs={"x": 2})
         metafunc.addcall(funcargs={"x": 3})
         pytest.raises(pytest.fail.Exception, "metafunc.addcall({'xyz': 0})")
         assert len(metafunc._calls) == 2
-        assert metafunc._calls[0].funcargs == {'x': 2}
-        assert metafunc._calls[1].funcargs == {'x': 3}
-        assert not hasattr(metafunc._calls[1], 'param')
+        assert metafunc._calls[0].funcargs == {"x": 2}
+        assert metafunc._calls[1].funcargs == {"x": 3}
+        assert not hasattr(metafunc._calls[1], "param")
 
     def test_parametrize_error(self):
+
         def func(x, y):
             pass
+
         metafunc = self.Metafunc(func)
         metafunc.parametrize("x", [1, 2])
         pytest.raises(ValueError, lambda: metafunc.parametrize("x", [5, 6]))
         pytest.raises(ValueError, lambda: metafunc.parametrize("x", [5, 6]))
         metafunc.parametrize("y", [1, 2])
         pytest.raises(ValueError, lambda: metafunc.parametrize("y", [5, 6]))
         pytest.raises(ValueError, lambda: metafunc.parametrize("y", [5, 6]))
 
     def test_parametrize_bad_scope(self, testdir):
+
         def func(x):
             pass
+
         metafunc = self.Metafunc(func)
         try:
-            metafunc.parametrize("x", [1], scope='doggy')
+            metafunc.parametrize("x", [1], scope="doggy")
         except ValueError as ve:
             assert "has an unsupported scope value 'doggy'" in str(ve)
 
     def test_parametrize_and_id(self):
+
         def func(x, y):
             pass
+
         metafunc = self.Metafunc(func)
 
-        metafunc.parametrize("x", [1, 2], ids=['basic', 'advanced'])
+        metafunc.parametrize("x", [1, 2], ids=["basic", "advanced"])
         metafunc.parametrize("y", ["abc", "def"])
         ids = [x.id for x in metafunc._calls]
         assert ids == ["basic-abc", "basic-def", "advanced-abc", "advanced-def"]
 
     def test_parametrize_and_id_unicode(self):
         """Allow unicode strings for "ids" parameter in Python 2 (##1905)"""
+
         def func(x):
             pass
+
         metafunc = self.Metafunc(func)
-        metafunc.parametrize("x", [1, 2], ids=[u'basic', u'advanced'])
+        metafunc.parametrize("x", [1, 2], ids=[u"basic", u"advanced"])
         ids = [x.id for x in metafunc._calls]
         assert ids == [u"basic", u"advanced"]
 
     def test_parametrize_with_wrong_number_of_ids(self, testdir):
+
         def func(x, y):
             pass
+
         metafunc = self.Metafunc(func)
 
-        pytest.raises(ValueError, lambda:
-                      metafunc.parametrize("x", [1, 2], ids=['basic']))
+        pytest.raises(
+            ValueError, lambda: metafunc.parametrize("x", [1, 2], ids=["basic"])
+        )
 
-        pytest.raises(ValueError, lambda:
-                      metafunc.parametrize(("x", "y"), [("abc", "def"),
-                                                        ("ghi", "jkl")], ids=["one"]))
+        pytest.raises(
+            ValueError,
+            lambda: metafunc.parametrize(
+                ("x", "y"), [("abc", "def"), ("ghi", "jkl")], ids=["one"]
+            ),
+        )
 
     @pytest.mark.issue510
     def test_parametrize_empty_list(self):
+
         def func(y):
             pass
-        metafunc = self.Metafunc(func)
+
+        class MockConfig(object):
+
+            def getini(self, name):
+                return ""
+
+            @property
+            def hook(self):
+                return self
+
+            def pytest_make_parametrize_id(self, **kw):
+                pass
+
+        metafunc = self.Metafunc(func, MockConfig())
         metafunc.parametrize("y", [])
-        assert 'skip' == metafunc._calls[0].marks[0].name
+        assert "skip" == metafunc._calls[0].marks[0].name
 
     def test_parametrize_with_userobjects(self):
+
         def func(x, y):
             pass
+
         metafunc = self.Metafunc(func)
 
         class A(object):
             pass
 
         metafunc.parametrize("x", [A(), A()])
         metafunc.parametrize("y", list("ab"))
         assert metafunc._calls[0].id == "x0-a"
         assert metafunc._calls[1].id == "x0-b"
         assert metafunc._calls[2].id == "x1-a"
         assert metafunc._calls[3].id == "x1-b"
 
     @hypothesis.given(strategies.text() | strategies.binary())
+    @hypothesis.settings(
+        deadline=400.0
+    )  # very close to std deadline and CI boxes are not reliable in CPU power
     def test_idval_hypothesis(self, value):
         from _pytest.python import _idval
-        escaped = _idval(value, 'a', 6, None)
+
+        escaped = _idval(value, "a", 6, None)
         assert isinstance(escaped, str)
         if PY3:
-            escaped.encode('ascii')
+            escaped.encode("ascii")
         else:
-            escaped.decode('ascii')
+            escaped.decode("ascii")
 
     def test_unicode_idval(self):
         """This tests that Unicode strings outside the ASCII character set get
         escaped, using byte escapes if they're in that range or unicode
         escapes if they're not.
 
         """
         from _pytest.python import _idval
+
         values = [
-            (
-                u'',
-                ''
-            ),
-            (
-                u'ascii',
-                'ascii'
-            ),
+            (u"", ""),
+            (u"ascii", "ascii"),
+            (u"ação", "a\\xe7\\xe3o"),
+            (u"josé@blah.com", "jos\\xe9@blah.com"),
             (
-                u'ação',
-                'a\\xe7\\xe3o'
-            ),
-            (
-                u'josé@blah.com',
-                'jos\\xe9@blah.com'
-            ),
-            (
-                u'δοκ.ιμή@παράδειγμα.δοκιμή',
-                '\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3'
-                '\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae'
+                u"δοκ.ιμή@παράδειγμα.δοκιμή",
+                "\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3"
+                "\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae",
             ),
         ]
         for val, expected in values:
-            assert _idval(val, 'a', 6, None) == expected
+            assert _idval(val, "a", 6, None) == expected
 
     def test_bytes_idval(self):
         """unittest for the expected behavior to obtain ids for parametrized
         bytes values:
         - python2: non-ascii strings are considered bytes and formatted using
         "binary escape", where any byte < 127 is escaped into its hex form.
         - python3: bytes objects are always escaped using "binary escape".
         """
         from _pytest.python import _idval
+
         values = [
-            (b'', ''),
-            (b'\xc3\xb4\xff\xe4', '\\xc3\\xb4\\xff\\xe4'),
-            (b'ascii', 'ascii'),
-            (u'αρά'.encode('utf-8'), '\\xce\\xb1\\xcf\\x81\\xce\\xac'),
+            (b"", ""),
+            (b"\xc3\xb4\xff\xe4", "\\xc3\\xb4\\xff\\xe4"),
+            (b"ascii", "ascii"),
+            (u"αρά".encode("utf-8"), "\\xce\\xb1\\xcf\\x81\\xce\\xac"),
         ]
         for val, expected in values:
-            assert _idval(val, 'a', 6, None) == expected
+            assert _idval(val, "a", 6, None) == expected
+
+    def test_class_or_function_idval(self):
+        """unittest for the expected behavior to obtain ids for parametrized
+        values that are classes or functions: their __name__.
+        """
+        from _pytest.python import _idval
+
+        class TestClass(object):
+            pass
+
+        def test_function():
+            pass
+
+        values = [(TestClass, "TestClass"), (test_function, "test_function")]
+        for val, expected in values:
+            assert _idval(val, "a", 6, None) == expected
 
     @pytest.mark.issue250
     def test_idmaker_autoname(self):
         from _pytest.python import idmaker
-        result = idmaker(("a", "b"), [pytest.param("string", 1.0),
-                                      pytest.param("st-ring", 2.0)])
+
+        result = idmaker(
+            ("a", "b"), [pytest.param("string", 1.0), pytest.param("st-ring", 2.0)]
+        )
         assert result == ["string-1.0", "st-ring-2.0"]
 
-        result = idmaker(("a", "b"), [pytest.param(object(), 1.0),
-                                      pytest.param(object(), object())])
+        result = idmaker(
+            ("a", "b"), [pytest.param(object(), 1.0), pytest.param(object(), object())]
+        )
         assert result == ["a0-1.0", "a1-b1"]
         # unicode mixing, issue250
         result = idmaker(
-            (py.builtin._totext("a"), "b"),
-            [pytest.param({}, b'\xc3\xb4')])
-        assert result == ['a0-\\xc3\\xb4']
+            (py.builtin._totext("a"), "b"), [pytest.param({}, b"\xc3\xb4")]
+        )
+        assert result == ["a0-\\xc3\\xb4"]
 
     def test_idmaker_with_bytes_regex(self):
         from _pytest.python import idmaker
-        result = idmaker(("a"), [pytest.param(re.compile(b'foo'), 1.0)])
+
+        result = idmaker(("a"), [pytest.param(re.compile(b"foo"), 1.0)])
         assert result == ["foo"]
 
     def test_idmaker_native_strings(self):
         from _pytest.python import idmaker
+
         totext = py.builtin._totext
-        result = idmaker(("a", "b"), [
-            pytest.param(1.0, -1.1),
-            pytest.param(2, -202),
-            pytest.param("three", "three hundred"),
-            pytest.param(True, False),
-            pytest.param(None, None),
-            pytest.param(re.compile('foo'), re.compile('bar')),
-            pytest.param(str, int),
-            pytest.param(list("six"), [66, 66]),
-            pytest.param(set([7]), set("seven")),
-            pytest.param(tuple("eight"), (8, -8, 8)),
-            pytest.param(b'\xc3\xb4', b"name"),
-            pytest.param(b'\xc3\xb4', totext("other")),
-        ])
-        assert result == ["1.0--1.1",
-                          "2--202",
-                          "three-three hundred",
-                          "True-False",
-                          "None-None",
-                          "foo-bar",
-                          "str-int",
-                          "a7-b7",
-                          "a8-b8",
-                          "a9-b9",
-                          "\\xc3\\xb4-name",
-                          "\\xc3\\xb4-other",
-                          ]
+        result = idmaker(
+            ("a", "b"),
+            [
+                pytest.param(1.0, -1.1),
+                pytest.param(2, -202),
+                pytest.param("three", "three hundred"),
+                pytest.param(True, False),
+                pytest.param(None, None),
+                pytest.param(re.compile("foo"), re.compile("bar")),
+                pytest.param(str, int),
+                pytest.param(list("six"), [66, 66]),
+                pytest.param({7}, set("seven")),
+                pytest.param(tuple("eight"), (8, -8, 8)),
+                pytest.param(b"\xc3\xb4", b"name"),
+                pytest.param(b"\xc3\xb4", totext("other")),
+            ],
+        )
+        assert (
+            result
+            == [
+                "1.0--1.1",
+                "2--202",
+                "three-three hundred",
+                "True-False",
+                "None-None",
+                "foo-bar",
+                "str-int",
+                "a7-b7",
+                "a8-b8",
+                "a9-b9",
+                "\\xc3\\xb4-name",
+                "\\xc3\\xb4-other",
+            ]
+        )
 
     def test_idmaker_enum(self):
         from _pytest.python import idmaker
+
         enum = pytest.importorskip("enum")
         e = enum.Enum("Foo", "one, two")
         result = idmaker(("a", "b"), [pytest.param(e.one, e.two)])
         assert result == ["Foo.one-Foo.two"]
 
     @pytest.mark.issue351
     def test_idmaker_idfn(self):
         from _pytest.python import idmaker
 
         def ids(val):
             if isinstance(val, Exception):
                 return repr(val)
 
-        result = idmaker(("a", "b"), [
-            pytest.param(10.0, IndexError()),
-            pytest.param(20, KeyError()),
-            pytest.param("three", [1, 2, 3]),
-        ], idfn=ids)
-        assert result == ["10.0-IndexError()",
-                          "20-KeyError()",
-                          "three-b2",
-                          ]
+        result = idmaker(
+            ("a", "b"),
+            [
+                pytest.param(10.0, IndexError()),
+                pytest.param(20, KeyError()),
+                pytest.param("three", [1, 2, 3]),
+            ],
+            idfn=ids,
+        )
+        assert result == ["10.0-IndexError()", "20-KeyError()", "three-b2"]
 
     @pytest.mark.issue351
     def test_idmaker_idfn_unique_names(self):
         from _pytest.python import idmaker
 
         def ids(val):
-            return 'a'
+            return "a"
 
-        result = idmaker(("a", "b"), [pytest.param(10.0, IndexError()),
-                                      pytest.param(20, KeyError()),
-                                      pytest.param("three", [1, 2, 3]),
-                                      ], idfn=ids)
-        assert result == ["a-a0",
-                          "a-a1",
-                          "a-a2",
-                          ]
+        result = idmaker(
+            ("a", "b"),
+            [
+                pytest.param(10.0, IndexError()),
+                pytest.param(20, KeyError()),
+                pytest.param("three", [1, 2, 3]),
+            ],
+            idfn=ids,
+        )
+        assert result == ["a-a0", "a-a1", "a-a2"]
 
     @pytest.mark.issue351
     def test_idmaker_idfn_exception(self):
         from _pytest.python import idmaker
         from _pytest.recwarn import WarningsRecorder
 
         class BadIdsException(Exception):
             pass
 
         def ids(val):
             raise BadIdsException("ids raised")
 
         rec = WarningsRecorder()
         with rec:
-            idmaker(("a", "b"), [
-                pytest.param(10.0, IndexError()),
-                pytest.param(20, KeyError()),
-                pytest.param("three", [1, 2, 3]),
-            ], idfn=ids)
+            idmaker(
+                ("a", "b"),
+                [
+                    pytest.param(10.0, IndexError()),
+                    pytest.param(20, KeyError()),
+                    pytest.param("three", [1, 2, 3]),
+                ],
+                idfn=ids,
+            )
 
-        assert [str(i.message) for i in rec.list] == [
-            "Raised while trying to determine id of parameter a at position 0."
-            "\nUpdate your code as this will raise an error in pytest-4.0.",
-            "Raised while trying to determine id of parameter b at position 0."
-            "\nUpdate your code as this will raise an error in pytest-4.0.",
-            "Raised while trying to determine id of parameter a at position 1."
-            "\nUpdate your code as this will raise an error in pytest-4.0.",
-            "Raised while trying to determine id of parameter b at position 1."
-            "\nUpdate your code as this will raise an error in pytest-4.0.",
-            "Raised while trying to determine id of parameter a at position 2."
-            "\nUpdate your code as this will raise an error in pytest-4.0.",
-            "Raised while trying to determine id of parameter b at position 2."
-            "\nUpdate your code as this will raise an error in pytest-4.0.",
-        ]
+        assert (
+            [str(i.message) for i in rec.list]
+            == [
+                "Raised while trying to determine id of parameter a at position 0."
+                "\nUpdate your code as this will raise an error in pytest-4.0.",
+                "Raised while trying to determine id of parameter b at position 0."
+                "\nUpdate your code as this will raise an error in pytest-4.0.",
+                "Raised while trying to determine id of parameter a at position 1."
+                "\nUpdate your code as this will raise an error in pytest-4.0.",
+                "Raised while trying to determine id of parameter b at position 1."
+                "\nUpdate your code as this will raise an error in pytest-4.0.",
+                "Raised while trying to determine id of parameter a at position 2."
+                "\nUpdate your code as this will raise an error in pytest-4.0.",
+                "Raised while trying to determine id of parameter b at position 2."
+                "\nUpdate your code as this will raise an error in pytest-4.0.",
+            ]
+        )
 
     def test_parametrize_ids_exception(self, testdir):
         """
         :param testdir: the instance of Testdir class, a temporary
         test directory.
         """
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
                 import pytest
 
                 def ids(arg):
                     raise Exception("bad ids")
 
                 @pytest.mark.parametrize("arg", ["a", "b"], ids=ids)
                 def test_foo(arg):
                     pass
-            """)
+            """
+        )
         with pytest.warns(DeprecationWarning):
             result = testdir.runpytest("--collect-only")
-        result.stdout.fnmatch_lines([
-            "<Module 'test_parametrize_ids_exception.py'>",
-            "  <Function 'test_foo[a]'>",
-            "  <Function 'test_foo[b]'>",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "<Module 'test_parametrize_ids_exception.py'>",
+                "  <Function 'test_foo[a]'>",
+                "  <Function 'test_foo[b]'>",
+            ]
+        )
 
     def test_idmaker_with_ids(self):
         from _pytest.python import idmaker
-        result = idmaker(("a", "b"), [pytest.param(1, 2),
-                                      pytest.param(3, 4)],
-                         ids=["a", None])
+
+        result = idmaker(
+            ("a", "b"), [pytest.param(1, 2), pytest.param(3, 4)], ids=["a", None]
+        )
         assert result == ["a", "3-4"]
 
     def test_idmaker_with_paramset_id(self):
         from _pytest.python import idmaker
-        result = idmaker(("a", "b"), [pytest.param(1, 2, id="me"),
-                                      pytest.param(3, 4, id="you")],
-                         ids=["a", None])
+
+        result = idmaker(
+            ("a", "b"),
+            [pytest.param(1, 2, id="me"), pytest.param(3, 4, id="you")],
+            ids=["a", None],
+        )
         assert result == ["me", "you"]
 
     def test_idmaker_with_ids_unique_names(self):
         from _pytest.python import idmaker
-        result = idmaker(("a"), map(pytest.param, [1, 2, 3, 4, 5]),
-                         ids=["a", "a", "b", "c", "b"])
+
+        result = idmaker(
+            ("a"), map(pytest.param, [1, 2, 3, 4, 5]), ids=["a", "a", "b", "c", "b"]
+        )
         assert result == ["a0", "a1", "b0", "c", "b1"]
 
     def test_addcall_and_parametrize(self):
+
         def func(x, y):
             pass
+
         metafunc = self.Metafunc(func)
-        metafunc.addcall({'x': 1})
-        metafunc.parametrize('y', [2, 3])
+        metafunc.addcall({"x": 1})
+        metafunc.parametrize("y", [2, 3])
         assert len(metafunc._calls) == 2
-        assert metafunc._calls[0].funcargs == {'x': 1, 'y': 2}
-        assert metafunc._calls[1].funcargs == {'x': 1, 'y': 3}
+        assert metafunc._calls[0].funcargs == {"x": 1, "y": 2}
+        assert metafunc._calls[1].funcargs == {"x": 1, "y": 3}
         assert metafunc._calls[0].id == "0-2"
         assert metafunc._calls[1].id == "0-3"
 
     @pytest.mark.issue714
     def test_parametrize_indirect(self):
+
         def func(x, y):
             pass
+
         metafunc = self.Metafunc(func)
-        metafunc.parametrize('x', [1], indirect=True)
-        metafunc.parametrize('y', [2, 3], indirect=True)
+        metafunc.parametrize("x", [1], indirect=True)
+        metafunc.parametrize("y", [2, 3], indirect=True)
         assert len(metafunc._calls) == 2
         assert metafunc._calls[0].funcargs == {}
         assert metafunc._calls[1].funcargs == {}
         assert metafunc._calls[0].params == dict(x=1, y=2)
         assert metafunc._calls[1].params == dict(x=1, y=3)
 
     @pytest.mark.issue714
     def test_parametrize_indirect_list(self):
+
         def func(x, y):
             pass
+
         metafunc = self.Metafunc(func)
-        metafunc.parametrize('x, y', [('a', 'b')], indirect=['x'])
-        assert metafunc._calls[0].funcargs == dict(y='b')
-        assert metafunc._calls[0].params == dict(x='a')
+        metafunc.parametrize("x, y", [("a", "b")], indirect=["x"])
+        assert metafunc._calls[0].funcargs == dict(y="b")
+        assert metafunc._calls[0].params == dict(x="a")
 
     @pytest.mark.issue714
     def test_parametrize_indirect_list_all(self):
+
         def func(x, y):
             pass
+
         metafunc = self.Metafunc(func)
-        metafunc.parametrize('x, y', [('a', 'b')], indirect=['x', 'y'])
+        metafunc.parametrize("x, y", [("a", "b")], indirect=["x", "y"])
         assert metafunc._calls[0].funcargs == {}
-        assert metafunc._calls[0].params == dict(x='a', y='b')
+        assert metafunc._calls[0].params == dict(x="a", y="b")
 
     @pytest.mark.issue714
     def test_parametrize_indirect_list_empty(self):
+
         def func(x, y):
             pass
+
         metafunc = self.Metafunc(func)
-        metafunc.parametrize('x, y', [('a', 'b')], indirect=[])
-        assert metafunc._calls[0].funcargs == dict(x='a', y='b')
+        metafunc.parametrize("x, y", [("a", "b")], indirect=[])
+        assert metafunc._calls[0].funcargs == dict(x="a", y="b")
         assert metafunc._calls[0].params == {}
 
     @pytest.mark.issue714
     def test_parametrize_indirect_list_functional(self, testdir):
         """
         Test parametrization with 'indirect' parameter applied on
         particular arguments. As y is is direct, its value should
         be used directly rather than being passed to the fixture
         y.
 
         :param testdir: the instance of Testdir class, a temporary
         test directory.
         """
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(scope='function')
             def x(request):
                 return request.param * 3
             @pytest.fixture(scope='function')
             def y(request):
                 return request.param * 2
             @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])
             def test_simple(x,y):
                 assert len(x) == 3
                 assert len(y) == 1
-        """)
+        """
+        )
         result = testdir.runpytest("-v")
-        result.stdout.fnmatch_lines([
-            "*test_simple*a-b*",
-            "*1 passed*",
-        ])
+        result.stdout.fnmatch_lines(["*test_simple*a-b*", "*1 passed*"])
 
     @pytest.mark.issue714
     def test_parametrize_indirect_list_error(self, testdir):
+
         def func(x, y):
             pass
+
         metafunc = self.Metafunc(func)
         with pytest.raises(ValueError):
-            metafunc.parametrize('x, y', [('a', 'b')], indirect=['x', 'z'])
+            metafunc.parametrize("x, y", [("a", "b")], indirect=["x", "z"])
 
     @pytest.mark.issue714
     def test_parametrize_uses_no_fixture_error_indirect_false(self, testdir):
         """The 'uses no fixture' error tells the user at collection time
         that the parametrize data they've set up doesn't correspond to the
         fixtures in their test function, rather than silently ignoring this
         and letting the test potentially pass.
         """
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=False)
             def test_simple(x):
                 assert len(x) == 3
-        """)
+        """
+        )
         result = testdir.runpytest("--collect-only")
-        result.stdout.fnmatch_lines([
-            "*uses no argument 'y'*",
-        ])
+        result.stdout.fnmatch_lines(["*uses no argument 'y'*"])
 
     @pytest.mark.issue714
     def test_parametrize_uses_no_fixture_error_indirect_true(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(scope='function')
             def x(request):
                 return request.param * 3
             @pytest.fixture(scope='function')
             def y(request):
                 return request.param * 2
 
             @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=True)
             def test_simple(x):
                 assert len(x) == 3
-        """)
+        """
+        )
         result = testdir.runpytest("--collect-only")
-        result.stdout.fnmatch_lines([
-            "*uses no fixture 'y'*",
-        ])
+        result.stdout.fnmatch_lines(["*uses no fixture 'y'*"])
 
     @pytest.mark.issue714
     def test_parametrize_indirect_uses_no_fixture_error_indirect_string(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(scope='function')
             def x(request):
                 return request.param * 3
 
             @pytest.mark.parametrize('x, y', [('a', 'b')], indirect='y')
             def test_simple(x):
                 assert len(x) == 3
-        """)
+        """
+        )
         result = testdir.runpytest("--collect-only")
-        result.stdout.fnmatch_lines([
-            "*uses no fixture 'y'*",
-        ])
+        result.stdout.fnmatch_lines(["*uses no fixture 'y'*"])
 
     @pytest.mark.issue714
     def test_parametrize_indirect_uses_no_fixture_error_indirect_list(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(scope='function')
             def x(request):
                 return request.param * 3
 
             @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['y'])
             def test_simple(x):
                 assert len(x) == 3
-        """)
+        """
+        )
         result = testdir.runpytest("--collect-only")
-        result.stdout.fnmatch_lines([
-            "*uses no fixture 'y'*",
-        ])
+        result.stdout.fnmatch_lines(["*uses no fixture 'y'*"])
 
     @pytest.mark.issue714
     def test_parametrize_argument_not_in_indirect_list(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(scope='function')
             def x(request):
                 return request.param * 3
 
             @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])
             def test_simple(x):
                 assert len(x) == 3
-        """)
+        """
+        )
         result = testdir.runpytest("--collect-only")
-        result.stdout.fnmatch_lines([
-            "*uses no argument 'y'*",
-        ])
+        result.stdout.fnmatch_lines(["*uses no argument 'y'*"])
+
+    def test_parametrize_gives_indicative_error_on_function_with_default_argument(
+        self, testdir
+    ):
+        testdir.makepyfile(
+            """
+            import pytest
+
+            @pytest.mark.parametrize('x, y', [('a', 'b')])
+            def test_simple(x, y=1):
+                assert len(x) == 1
+        """
+        )
+        result = testdir.runpytest("--collect-only")
+        result.stdout.fnmatch_lines(
+            ["*already takes an argument 'y' with a default value"]
+        )
 
     def test_addcalls_and_parametrize_indirect(self):
+
         def func(x, y):
             pass
+
         metafunc = self.Metafunc(func)
         metafunc.addcall(param="123")
-        metafunc.parametrize('x', [1], indirect=True)
-        metafunc.parametrize('y', [2, 3], indirect=True)
+        metafunc.parametrize("x", [1], indirect=True)
+        metafunc.parametrize("y", [2, 3], indirect=True)
         assert len(metafunc._calls) == 2
         assert metafunc._calls[0].funcargs == {}
         assert metafunc._calls[1].funcargs == {}
         assert metafunc._calls[0].params == dict(x=1, y=2)
         assert metafunc._calls[1].params == dict(x=1, y=3)
 
     def test_parametrize_functional(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def pytest_generate_tests(metafunc):
                 metafunc.parametrize('x', [1,2], indirect=True)
                 metafunc.parametrize('y', [2])
             @pytest.fixture
             def x(request):
                 return request.param * 10
 
             def test_simple(x,y):
                 assert x in (10,20)
                 assert y == 2
-        """)
+        """
+        )
         result = testdir.runpytest("-v")
-        result.stdout.fnmatch_lines([
-            "*test_simple*1-2*",
-            "*test_simple*2-2*",
-            "*2 passed*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*test_simple*1-2*", "*test_simple*2-2*", "*2 passed*"]
+        )
 
     def test_parametrize_onearg(self):
         metafunc = self.Metafunc(lambda x: None)
         metafunc.parametrize("x", [1, 2])
         assert len(metafunc._calls) == 2
         assert metafunc._calls[0].funcargs == dict(x=1)
         assert metafunc._calls[0].id == "1"
         assert metafunc._calls[1].funcargs == dict(x=2)
@@ -641,42 +761,47 @@ class TestMetafunc(object):
         metafunc.parametrize(("x", "y"), [(1, 2), (3, 4)])
         assert len(metafunc._calls) == 2
         assert metafunc._calls[0].funcargs == dict(x=1, y=2)
         assert metafunc._calls[0].id == "1-2"
         assert metafunc._calls[1].funcargs == dict(x=3, y=4)
         assert metafunc._calls[1].id == "3-4"
 
     def test_parametrize_multiple_times(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             pytestmark = pytest.mark.parametrize("x", [1,2])
             def test_func(x):
                 assert 0, x
             class TestClass(object):
                 pytestmark = pytest.mark.parametrize("y", [3,4])
                 def test_meth(self, x, y):
                     assert 0, x
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == 1
         result.assert_outcomes(failed=6)
 
     def test_parametrize_CSV(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.parametrize("x, y,", [(1,2), (2,3)])
             def test_func(x, y):
                 assert x+1 == y
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2)
 
     def test_parametrize_class_scenarios(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
         # same as doc/en/example/parametrize scenario example
         def pytest_generate_tests(metafunc):
             idlist = []
             argvalues = []
             for scenario in metafunc.cls.scenarios:
                 idlist.append(scenario[0])
                 items = scenario[1].items()
                 argnames = [x[0] for x in items]
@@ -690,52 +815,62 @@ class TestMetafunc(object):
                def test_1(self, arg, arg2):
                   pass
 
                def test_2(self, arg2, arg):
                   pass
 
                def test_3(self, arg, arg2):
                   pass
-        """)
+        """
+        )
         result = testdir.runpytest("-v")
         assert result.ret == 0
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *test_1*1*
             *test_2*1*
             *test_3*1*
             *test_1*2*
             *test_2*2*
             *test_3*2*
             *6 passed*
-        """)
+        """
+        )
 
     def test_format_args(self):
+
         def function1():
             pass
-        assert fixtures._format_args(function1) == '()'
+
+        assert fixtures._format_args(function1) == "()"
 
         def function2(arg1):
             pass
+
         assert fixtures._format_args(function2) == "(arg1)"
 
         def function3(arg1, arg2="qwe"):
             pass
+
         assert fixtures._format_args(function3) == "(arg1, arg2='qwe')"
 
         def function4(arg1, *args, **kwargs):
             pass
+
         assert fixtures._format_args(function4) == "(arg1, *args, **kwargs)"
 
 
 class TestMetafuncFunctional(object):
+
     def test_attributes(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             # assumes that generate/provide runs in the same process
-            import py, pytest
+            import sys, pytest
             def pytest_generate_tests(metafunc):
                 metafunc.addcall(param=metafunc)
 
             @pytest.fixture
             def metafunc(request):
                 assert request._pyfuncitem._genid == "0"
                 return request.param
 
@@ -744,504 +879,564 @@ class TestMetafuncFunctional(object):
                 assert metafunc.module.__name__ == __name__
                 assert metafunc.function == test_function
                 assert metafunc.cls is None
 
             class TestClass(object):
                 def test_method(self, metafunc, pytestconfig):
                     assert metafunc.config == pytestconfig
                     assert metafunc.module.__name__ == __name__
-                    if py.std.sys.version_info > (3, 0):
+                    if sys.version_info > (3, 0):
                         unbound = TestClass.test_method
                     else:
                         unbound = TestClass.test_method.im_func
                     # XXX actually have an unbound test function here?
                     assert metafunc.function == unbound
                     assert metafunc.cls == TestClass
-        """)
+        """
+        )
         result = testdir.runpytest(p, "-v")
         result.assert_outcomes(passed=2)
 
     def test_addcall_with_two_funcargs_generators(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_generate_tests(metafunc):
                 assert "arg1" in metafunc.fixturenames
                 metafunc.addcall(funcargs=dict(arg1=1, arg2=2))
-        """)
-        p = testdir.makepyfile("""
+        """
+        )
+        p = testdir.makepyfile(
+            """
             def pytest_generate_tests(metafunc):
                 metafunc.addcall(funcargs=dict(arg1=1, arg2=1))
 
             class TestClass(object):
                 def test_myfunc(self, arg1, arg2):
                     assert arg1 == arg2
-        """)
+        """
+        )
         result = testdir.runpytest("-v", p)
-        result.stdout.fnmatch_lines([
-            "*test_myfunc*0*PASS*",
-            "*test_myfunc*1*FAIL*",
-            "*1 failed, 1 passed*"
-        ])
+        result.stdout.fnmatch_lines(
+            ["*test_myfunc*0*PASS*", "*test_myfunc*1*FAIL*", "*1 failed, 1 passed*"]
+        )
 
     def test_two_functions(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def pytest_generate_tests(metafunc):
                 metafunc.addcall(param=10)
                 metafunc.addcall(param=20)
 
             import pytest
             @pytest.fixture
             def arg1(request):
                 return request.param
 
             def test_func1(arg1):
                 assert arg1 == 10
             def test_func2(arg1):
                 assert arg1 in (10, 20)
-        """)
+        """
+        )
         result = testdir.runpytest("-v", p)
-        result.stdout.fnmatch_lines([
-            "*test_func1*0*PASS*",
-            "*test_func1*1*FAIL*",
-            "*test_func2*PASS*",
-            "*1 failed, 3 passed*"
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*test_func1*0*PASS*",
+                "*test_func1*1*FAIL*",
+                "*test_func2*PASS*",
+                "*1 failed, 3 passed*",
+            ]
+        )
 
     def test_noself_in_method(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def pytest_generate_tests(metafunc):
                 assert 'xyz' not in metafunc.fixturenames
 
             class TestHello(object):
                 def test_hello(xyz):
                     pass
-        """)
+        """
+        )
         result = testdir.runpytest(p)
         result.assert_outcomes(passed=1)
 
     def test_generate_plugin_and_module(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_generate_tests(metafunc):
                 assert "arg1" in metafunc.fixturenames
                 metafunc.addcall(id="world", param=(2,100))
-        """)
-        p = testdir.makepyfile("""
+        """
+        )
+        p = testdir.makepyfile(
+            """
             def pytest_generate_tests(metafunc):
                 metafunc.addcall(param=(1,1), id="hello")
 
             import pytest
             @pytest.fixture
             def arg1(request):
                 return request.param[0]
             @pytest.fixture
             def arg2(request):
                 return request.param[1]
 
             class TestClass(object):
                 def test_myfunc(self, arg1, arg2):
                     assert arg1 == arg2
-        """)
+        """
+        )
         result = testdir.runpytest("-v", p)
-        result.stdout.fnmatch_lines([
-            "*test_myfunc*hello*PASS*",
-            "*test_myfunc*world*FAIL*",
-            "*1 failed, 1 passed*"
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*test_myfunc*hello*PASS*",
+                "*test_myfunc*world*FAIL*",
+                "*1 failed, 1 passed*",
+            ]
+        )
 
     def test_generate_tests_in_class(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             class TestClass(object):
                 def pytest_generate_tests(self, metafunc):
                     metafunc.addcall(funcargs={'hello': 'world'}, id="hello")
 
                 def test_myfunc(self, hello):
                     assert hello == "world"
-        """)
+        """
+        )
         result = testdir.runpytest("-v", p)
-        result.stdout.fnmatch_lines([
-            "*test_myfunc*hello*PASS*",
-            "*1 passed*"
-        ])
+        result.stdout.fnmatch_lines(["*test_myfunc*hello*PASS*", "*1 passed*"])
 
     def test_two_functions_not_same_instance(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def pytest_generate_tests(metafunc):
                 metafunc.addcall({'arg1': 10})
                 metafunc.addcall({'arg1': 20})
 
             class TestClass(object):
                 def test_func(self, arg1):
                     assert not hasattr(self, 'x')
                     self.x = 1
-        """)
+        """
+        )
         result = testdir.runpytest("-v", p)
-        result.stdout.fnmatch_lines([
-            "*test_func*0*PASS*",
-            "*test_func*1*PASS*",
-            "*2 pass*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*test_func*0*PASS*", "*test_func*1*PASS*", "*2 pass*"]
+        )
 
     def test_issue28_setup_method_in_generate_tests(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def pytest_generate_tests(metafunc):
                 metafunc.addcall({'arg1': 1})
 
             class TestClass(object):
                 def test_method(self, arg1):
                     assert arg1 == self.val
                 def setup_method(self, func):
                     self.val = 1
-            """)
+            """
+        )
         result = testdir.runpytest(p)
         result.assert_outcomes(passed=1)
 
     def test_parametrize_functional2(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def pytest_generate_tests(metafunc):
                 metafunc.parametrize("arg1", [1,2])
                 metafunc.parametrize("arg2", [4,5])
             def test_hello(arg1, arg2):
                 assert 0, (arg1, arg2)
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*(1, 4)*",
-            "*(1, 5)*",
-            "*(2, 4)*",
-            "*(2, 5)*",
-            "*4 failed*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*(1, 4)*", "*(1, 5)*", "*(2, 4)*", "*(2, 5)*", "*4 failed*"]
+        )
 
     def test_parametrize_and_inner_getfixturevalue(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def pytest_generate_tests(metafunc):
                 metafunc.parametrize("arg1", [1], indirect=True)
                 metafunc.parametrize("arg2", [10], indirect=True)
 
             import pytest
             @pytest.fixture
             def arg1(request):
                 x = request.getfixturevalue("arg2")
                 return x + request.param
 
             @pytest.fixture
             def arg2(request):
                 return request.param
 
             def test_func1(arg1, arg2):
                 assert arg1 == 11
-        """)
+        """
+        )
         result = testdir.runpytest("-v", p)
-        result.stdout.fnmatch_lines([
-            "*test_func1*1*PASS*",
-            "*1 passed*"
-        ])
+        result.stdout.fnmatch_lines(["*test_func1*1*PASS*", "*1 passed*"])
 
     def test_parametrize_on_setup_arg(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def pytest_generate_tests(metafunc):
                 assert "arg1" in metafunc.fixturenames
                 metafunc.parametrize("arg1", [1], indirect=True)
 
             import pytest
             @pytest.fixture
             def arg1(request):
                 return request.param
 
             @pytest.fixture
             def arg2(request, arg1):
                 return 10 * arg1
 
             def test_func(arg2):
                 assert arg2 == 10
-        """)
+        """
+        )
         result = testdir.runpytest("-v", p)
-        result.stdout.fnmatch_lines([
-            "*test_func*1*PASS*",
-            "*1 passed*"
-        ])
+        result.stdout.fnmatch_lines(["*test_func*1*PASS*", "*1 passed*"])
 
     def test_parametrize_with_ids(self, testdir):
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
             console_output_style=classic
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             import pytest
             def pytest_generate_tests(metafunc):
                 metafunc.parametrize(("a", "b"), [(1,1), (1,2)],
                                      ids=["basic", "advanced"])
 
             def test_function(a, b):
                 assert a == b
-        """)
+        """
+        )
         result = testdir.runpytest("-v")
         assert result.ret == 1
-        result.stdout.fnmatch_lines_random([
-            "*test_function*basic*PASSED",
-            "*test_function*advanced*FAILED",
-        ])
+        result.stdout.fnmatch_lines_random(
+            ["*test_function*basic*PASSED", "*test_function*advanced*FAILED"]
+        )
 
     def test_parametrize_without_ids(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def pytest_generate_tests(metafunc):
                 metafunc.parametrize(("a", "b"),
                                      [(1,object()), (1.3,object())])
 
             def test_function(a, b):
                 assert 1
-        """)
+        """
+        )
         result = testdir.runpytest("-v")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *test_function*1-b0*
             *test_function*1.3-b1*
-        """)
+        """
+        )
 
     def test_parametrize_with_None_in_ids(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def pytest_generate_tests(metafunc):
                 metafunc.parametrize(("a", "b"), [(1,1), (1,1), (1,2)],
                                      ids=["basic", None, "advanced"])
 
             def test_function(a, b):
                 assert a == b
-        """)
+        """
+        )
         result = testdir.runpytest("-v")
         assert result.ret == 1
-        result.stdout.fnmatch_lines_random([
-            "*test_function*basic*PASSED*",
-            "*test_function*1-1*PASSED*",
-            "*test_function*advanced*FAILED*",
-        ])
+        result.stdout.fnmatch_lines_random(
+            [
+                "*test_function*basic*PASSED*",
+                "*test_function*1-1*PASSED*",
+                "*test_function*advanced*FAILED*",
+            ]
+        )
 
     def test_fixture_parametrized_empty_ids(self, testdir):
         """Fixtures parametrized with empty ids cause an internal error (#1849)."""
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(scope="module", ids=[], params=[])
             def temp(request):
                return request.param
 
             def test_temp(temp):
                  pass
-        ''')
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines(['* 1 skipped *'])
+        result.stdout.fnmatch_lines(["* 1 skipped *"])
 
     def test_parametrized_empty_ids(self, testdir):
         """Tests parametrized with empty ids cause an internal error (#1849)."""
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.mark.parametrize('temp', [], ids=list())
             def test_temp(temp):
                  pass
-        ''')
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines(['* 1 skipped *'])
+        result.stdout.fnmatch_lines(["* 1 skipped *"])
 
     def test_parametrized_ids_invalid_type(self, testdir):
         """Tests parametrized with ids as non-strings (#1857)."""
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.mark.parametrize("x, expected", [(10, 20), (40, 80)], ids=(None, 2))
             def test_ids_numbers(x,expected):
                 assert x * 2 == expected
-        ''')
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines(['*ids must be list of strings, found: 2 (type: int)*'])
+        result.stdout.fnmatch_lines(
+            ["*ids must be list of strings, found: 2 (type: int)*"]
+        )
 
     def test_parametrize_with_identical_ids_get_unique_names(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def pytest_generate_tests(metafunc):
                 metafunc.parametrize(("a", "b"), [(1,1), (1,2)],
                                      ids=["a", "a"])
 
             def test_function(a, b):
                 assert a == b
-        """)
+        """
+        )
         result = testdir.runpytest("-v")
         assert result.ret == 1
-        result.stdout.fnmatch_lines_random([
-            "*test_function*a0*PASSED*",
-            "*test_function*a1*FAILED*"
-        ])
+        result.stdout.fnmatch_lines_random(
+            ["*test_function*a0*PASSED*", "*test_function*a1*FAILED*"]
+        )
 
-    @pytest.mark.parametrize(("scope", "length"),
-                             [("module", 2), ("function", 4)])
+    @pytest.mark.parametrize(("scope", "length"), [("module", 2), ("function", 4)])
     def test_parametrize_scope_overrides(self, testdir, scope, length):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             values = []
             def pytest_generate_tests(metafunc):
                 if "arg" in metafunc.funcargnames:
                     metafunc.parametrize("arg", [1,2], indirect=True,
                                          scope=%r)
             @pytest.fixture
             def arg(request):
                 values.append(request.param)
                 return request.param
             def test_hello(arg):
                 assert arg in (1,2)
             def test_world(arg):
                 assert arg in (1,2)
             def test_checklength():
                 assert len(values) == %d
-        """ % (scope, length))
+        """
+            % (scope, length)
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=5)
 
     def test_parametrize_issue323(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(scope='module', params=range(966))
             def foo(request):
                 return request.param
 
             def test_it(foo):
                 pass
             def test_it2(foo):
                 pass
-        """)
+        """
+        )
         reprec = testdir.inline_run("--collect-only")
         assert not reprec.getcalls("pytest_internalerror")
 
     def test_usefixtures_seen_in_generate_tests(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def pytest_generate_tests(metafunc):
                 assert "abc" in metafunc.fixturenames
                 metafunc.parametrize("abc", [1])
 
             @pytest.mark.usefixtures("abc")
             def test_function():
                 pass
-        """)
+        """
+        )
         reprec = testdir.runpytest()
         reprec.assert_outcomes(passed=1)
 
     def test_generate_tests_only_done_in_subdir(self, testdir):
         sub1 = testdir.mkpydir("sub1")
         sub2 = testdir.mkpydir("sub2")
-        sub1.join("conftest.py").write(_pytest._code.Source("""
+        sub1.join("conftest.py").write(
+            _pytest._code.Source(
+                """
             def pytest_generate_tests(metafunc):
                 assert metafunc.function.__name__ == "test_1"
-        """))
-        sub2.join("conftest.py").write(_pytest._code.Source("""
+        """
+            )
+        )
+        sub2.join("conftest.py").write(
+            _pytest._code.Source(
+                """
             def pytest_generate_tests(metafunc):
                 assert metafunc.function.__name__ == "test_2"
-        """))
+        """
+            )
+        )
         sub1.join("test_in_sub1.py").write("def test_1(): pass")
         sub2.join("test_in_sub2.py").write("def test_2(): pass")
         result = testdir.runpytest("--keep-duplicates", "-v", "-s", sub1, sub2, sub1)
         result.assert_outcomes(passed=3)
 
     def test_generate_same_function_names_issue403(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             def make_tests():
                 @pytest.mark.parametrize("x", range(2))
                 def test_foo(x):
                     pass
                 return test_foo
 
             test_x = make_tests()
             test_y = make_tests()
-        """)
+        """
+        )
         reprec = testdir.runpytest()
         reprec.assert_outcomes(passed=4)
 
     @pytest.mark.issue463
-    @pytest.mark.parametrize('attr', ['parametrise', 'parameterize',
-                                      'parameterise'])
+    @pytest.mark.parametrize("attr", ["parametrise", "parameterize", "parameterise"])
     def test_parametrize_misspelling(self, testdir, attr):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
-            @pytest.mark.{0}("x", range(2))
+            @pytest.mark.{}("x", range(2))
             def test_foo(x):
                 pass
-        """.format(attr))
-        reprec = testdir.inline_run('--collectonly')
+        """.format(
+                attr
+            )
+        )
+        reprec = testdir.inline_run("--collectonly")
         failures = reprec.getfailures()
         assert len(failures) == 1
-        expectederror = "MarkerError: test_foo has '{0}', spelling should be 'parametrize'".format(attr)
+        expectederror = "MarkerError: test_foo has '{}', spelling should be 'parametrize'".format(
+            attr
+        )
         assert expectederror in failures[0].longrepr.reprcrash.message
 
 
 class TestMetafuncFunctionalAuto(object):
     """
     Tests related to automatically find out the correct scope for parametrized tests (#1832).
     """
 
     def test_parametrize_auto_scope(self, testdir):
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(scope='session', autouse=True)
             def fixture():
                 return 1
 
             @pytest.mark.parametrize('animal', ["dog", "cat"])
             def test_1(animal):
                 assert animal in ('dog', 'cat')
 
             @pytest.mark.parametrize('animal', ['fish'])
             def test_2(animal):
                 assert animal == 'fish'
 
-        ''')
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines(['* 3 passed *'])
+        result.stdout.fnmatch_lines(["* 3 passed *"])
 
     def test_parametrize_auto_scope_indirect(self, testdir):
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(scope='session')
             def echo(request):
                 return request.param
 
             @pytest.mark.parametrize('animal, echo', [("dog", 1), ("cat", 2)], indirect=['echo'])
             def test_1(animal, echo):
                 assert animal in ('dog', 'cat')
                 assert echo in (1, 2, 3)
 
             @pytest.mark.parametrize('animal, echo', [('fish', 3)], indirect=['echo'])
             def test_2(animal, echo):
                 assert animal == 'fish'
                 assert echo in (1, 2, 3)
-        ''')
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines(['* 3 passed *'])
+        result.stdout.fnmatch_lines(["* 3 passed *"])
 
     def test_parametrize_auto_scope_override_fixture(self, testdir):
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(scope='session', autouse=True)
             def animal():
                 return 'fox'
 
             @pytest.mark.parametrize('animal', ["dog", "cat"])
             def test_1(animal):
                 assert animal in ('dog', 'cat')
-        ''')
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines(['* 2 passed *'])
+        result.stdout.fnmatch_lines(["* 2 passed *"])
 
     def test_parametrize_all_indirects(self, testdir):
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture()
             def animal(request):
                 return request.param
 
             @pytest.fixture(scope='session')
             def echo(request):
@@ -1251,22 +1446,24 @@ class TestMetafuncFunctionalAuto(object)
             def test_1(animal, echo):
                 assert animal in ('dog', 'cat')
                 assert echo in (1, 2, 3)
 
             @pytest.mark.parametrize('animal, echo', [("fish", 3)], indirect=True)
             def test_2(animal, echo):
                 assert animal == 'fish'
                 assert echo in (1, 2, 3)
-        ''')
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines(['* 3 passed *'])
+        result.stdout.fnmatch_lines(["* 3 passed *"])
 
     def test_parametrize_issue634(self, testdir):
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture(scope='module')
             def foo(request):
                 print('preparing foo-%d' % request.param)
                 return 'foo-%d' % request.param
 
             def test_one(foo):
@@ -1281,24 +1478,25 @@ class TestMetafuncFunctionalAuto(object)
                 params = (1, 2, 3, 4)
                 if not 'foo' in metafunc.fixturenames:
                     return
 
                 test_with = getattr(metafunc.function, 'test_with', None)
                 if test_with:
                     params = test_with
                 metafunc.parametrize('foo', params, indirect=True)
-        ''')
+        """
+        )
         result = testdir.runpytest("-s")
         output = result.stdout.str()
-        assert output.count('preparing foo-2') == 1
-        assert output.count('preparing foo-3') == 1
+        assert output.count("preparing foo-2") == 1
+        assert output.count("preparing foo-3") == 1
 
 
-@pytest.mark.filterwarnings('ignore:Applying marks directly to parameters')
+@pytest.mark.filterwarnings("ignore:Applying marks directly to parameters")
 @pytest.mark.issue308
 class TestMarkersWithParametrization(object):
 
     def test_simple_mark(self, testdir):
         s = """
             import pytest
 
             @pytest.mark.foo
@@ -1308,35 +1506,35 @@ class TestMarkersWithParametrization(obj
                 (2, 3),
             ])
             def test_increment(n, expected):
                 assert n + 1 == expected
         """
         items = testdir.getitems(s)
         assert len(items) == 3
         for item in items:
-            assert 'foo' in item.keywords
-        assert 'bar' not in items[0].keywords
-        assert 'bar' in items[1].keywords
-        assert 'bar' not in items[2].keywords
+            assert "foo" in item.keywords
+        assert "bar" not in items[0].keywords
+        assert "bar" in items[1].keywords
+        assert "bar" not in items[2].keywords
 
     def test_select_based_on_mark(self, testdir):
         s = """
             import pytest
 
             @pytest.mark.parametrize(("n", "expected"), [
                 (1, 2),
                 pytest.mark.foo((2, 3)),
                 (3, 4),
             ])
             def test_increment(n, expected):
                 assert n + 1 == expected
         """
         testdir.makepyfile(s)
-        rec = testdir.inline_run("-m", 'foo')
+        rec = testdir.inline_run("-m", "foo")
         passed, skipped, fail = rec.listoutcomes()
         assert len(passed) == 1
         assert len(skipped) == 0
         assert len(fail) == 0
 
     @pytest.mark.xfail(reason="is this important to support??")
     def test_nested_marks(self, testdir):
         s = """
@@ -1348,17 +1546,17 @@ class TestMarkersWithParametrization(obj
                 mastermark((1, 3)),
                 (2, 3),
             ])
             def test_increment(n, expected):
                 assert n + 1 == expected
         """
         items = testdir.getitems(s)
         assert len(items) == 3
-        for mark in ['foo', 'bar']:
+        for mark in ["foo", "bar"]:
             assert mark not in items[0].keywords
             assert mark in items[1].keywords
             assert mark not in items[2].keywords
 
     def test_simple_xfail(self, testdir):
         s = """
             import pytest
 
@@ -1434,29 +1632,31 @@ class TestMarkersWithParametrization(obj
             ])
             def test_increment(n, expected):
                 assert n + 1 == expected
         """
         testdir.makepyfile(s)
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2, skipped=1)
 
-    @pytest.mark.parametrize('strict', [True, False])
+    @pytest.mark.parametrize("strict", [True, False])
     def test_xfail_passing_is_xpass(self, testdir, strict):
         s = """
             import pytest
 
             @pytest.mark.parametrize(("n", "expected"), [
                 (1, 2),
                 pytest.mark.xfail("sys.version_info > (0, 0, 0)", reason="some bug", strict={strict})((2, 3)),
                 (3, 4),
             ])
             def test_increment(n, expected):
                 assert n + 1 == expected
-        """.format(strict=strict)
+        """.format(
+            strict=strict
+        )
         testdir.makepyfile(s)
         reprec = testdir.inline_run()
         passed, failed = (2, 1) if strict else (3, 0)
         reprec.assertoutcome(passed=passed, failed=failed)
 
     def test_parametrize_called_in_generate_tests(self, testdir):
         s = """
             import pytest
@@ -1477,85 +1677,92 @@ class TestMarkersWithParametrization(obj
                 assert n + 1 == expected
         """
         testdir.makepyfile(s)
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2, skipped=2)
 
     @pytest.mark.issue290
     def test_parametrize_ID_generation_string_int_works(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def myfixture():
                 return 'example'
             @pytest.mark.parametrize(
                 'limit', (0, '0'))
             def test_limit(limit, myfixture):
                 return
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=2)
 
-    @pytest.mark.parametrize('strict', [True, False])
+    @pytest.mark.parametrize("strict", [True, False])
     def test_parametrize_marked_value(self, testdir, strict):
         s = """
             import pytest
 
             @pytest.mark.parametrize(("n", "expected"), [
                 pytest.param(
                     2,3,
                     marks=pytest.mark.xfail("sys.version_info > (0, 0, 0)", reason="some bug", strict={strict}),
                 ),
                 pytest.param(
                     2,3,
                     marks=[pytest.mark.xfail("sys.version_info > (0, 0, 0)", reason="some bug", strict={strict})],
                 ),
             ])
             def test_increment(n, expected):
                 assert n + 1 == expected
-        """.format(strict=strict)
+        """.format(
+            strict=strict
+        )
         testdir.makepyfile(s)
         reprec = testdir.inline_run()
         passed, failed = (0, 2) if strict else (2, 0)
         reprec.assertoutcome(passed=passed, failed=failed)
 
     def test_pytest_make_parametrize_id(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_make_parametrize_id(config, val):
                 return str(val * 2)
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
                 import pytest
 
                 @pytest.mark.parametrize("x", range(2))
                 def test_func(x):
                     pass
-                """)
+                """
+        )
         result = testdir.runpytest("-v")
-        result.stdout.fnmatch_lines([
-            "*test_func*0*PASS*",
-            "*test_func*2*PASS*",
-        ])
+        result.stdout.fnmatch_lines(["*test_func*0*PASS*", "*test_func*2*PASS*"])
 
     def test_pytest_make_parametrize_id_with_argname(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_make_parametrize_id(config, val, argname):
                 return str(val * 2 if argname == 'x' else val * 10)
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
                 import pytest
 
                 @pytest.mark.parametrize("x", range(2))
                 def test_func_a(x):
                     pass
 
                 @pytest.mark.parametrize("y", [1])
                 def test_func_b(y):
                     pass
-                """)
+                """
+        )
         result = testdir.runpytest("-v")
-        result.stdout.fnmatch_lines([
-            "*test_func_a*0*PASS*",
-            "*test_func_a*2*PASS*",
-            "*test_func_b*10*PASS*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*test_func_a*0*PASS*", "*test_func_a*2*PASS*", "*test_func_b*10*PASS*"]
+        )
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/python/raises.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/python/raises.py
@@ -1,40 +1,46 @@
+from _pytest.outcomes import Failed
 import pytest
 import sys
 
 
 class TestRaises(object):
+
     def test_raises(self):
         source = "int('qwe')"
         excinfo = pytest.raises(ValueError, source)
         code = excinfo.traceback[-1].frame.code
         s = str(code.fullsource)
         assert s == source
 
     def test_raises_exec(self):
         pytest.raises(ValueError, "a,x = []")
 
     def test_raises_syntax_error(self):
         pytest.raises(SyntaxError, "qwe qwe qwe")
 
     def test_raises_function(self):
-        pytest.raises(ValueError, int, 'hello')
+        pytest.raises(ValueError, int, "hello")
 
     def test_raises_callable_no_exception(self):
+
         class A(object):
+
             def __call__(self):
                 pass
+
         try:
             pytest.raises(ValueError, A())
         except pytest.raises.Exception:
             pass
 
     def test_raises_as_contextmanager(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             from __future__ import with_statement
             import py, pytest
             import _pytest._code
 
             def test_simple():
                 with pytest.raises(ZeroDivisionError) as excinfo:
                     assert isinstance(excinfo, _pytest._code.ExceptionInfo)
                     1/0
@@ -46,69 +52,74 @@ class TestRaises(object):
                 with pytest.raises(pytest.raises.Exception):
                     with pytest.raises(ValueError):
                            int()
 
             def test_raise_wrong_exception_passes_by():
                 with pytest.raises(ZeroDivisionError):
                     with pytest.raises(ValueError):
                            1/0
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            '*3 passed*',
-        ])
+        result.stdout.fnmatch_lines(["*3 passed*"])
 
     def test_noclass(self):
         with pytest.raises(TypeError):
-            pytest.raises('wrong', lambda: None)
+            pytest.raises("wrong", lambda: None)
+
+    def test_invalid_arguments_to_raises(self):
+        with pytest.raises(TypeError, match="unknown"):
+            with pytest.raises(TypeError, unknown="bogus"):
+                raise ValueError()
 
     def test_tuple(self):
         with pytest.raises((KeyError, ValueError)):
-            raise KeyError('oops')
+            raise KeyError("oops")
 
     def test_no_raise_message(self):
         try:
-            pytest.raises(ValueError, int, '0')
+            pytest.raises(ValueError, int, "0")
         except pytest.raises.Exception as e:
-            assert e.msg == "DID NOT RAISE {0}".format(repr(ValueError))
+            assert e.msg == "DID NOT RAISE {}".format(repr(ValueError))
         else:
             assert False, "Expected pytest.raises.Exception"
 
         try:
             with pytest.raises(ValueError):
                 pass
         except pytest.raises.Exception as e:
-            assert e.msg == "DID NOT RAISE {0}".format(repr(ValueError))
+            assert e.msg == "DID NOT RAISE {}".format(repr(ValueError))
         else:
             assert False, "Expected pytest.raises.Exception"
 
     def test_custom_raise_message(self):
         message = "TEST_MESSAGE"
         try:
             with pytest.raises(ValueError, message=message):
                 pass
         except pytest.raises.Exception as e:
             assert e.msg == message
         else:
             assert False, "Expected pytest.raises.Exception"
 
-    @pytest.mark.parametrize('method', ['function', 'with'])
+    @pytest.mark.parametrize("method", ["function", "with"])
     def test_raises_cyclic_reference(self, method):
         """
         Ensure pytest.raises does not leave a reference cycle (#1965).
         """
         import gc
 
         class T(object):
+
             def __call__(self):
                 raise ValueError
 
         t = T()
-        if method == 'function':
+        if method == "function":
             pytest.raises(ValueError, t)
         else:
             with pytest.raises(ValueError):
                 t()
 
         # ensure both forms of pytest.raises don't leave exceptions in sys.exc_info()
         assert sys.exc_info() == (None, None, None)
 
@@ -116,19 +127,51 @@ class TestRaises(object):
 
         # ensure the t instance is not stuck in a cyclic reference
         for o in gc.get_objects():
             assert type(o) is not T
 
     def test_raises_match(self):
         msg = r"with base \d+"
         with pytest.raises(ValueError, match=msg):
-            int('asdf')
+            int("asdf")
 
         msg = "with base 10"
         with pytest.raises(ValueError, match=msg):
-            int('asdf')
+            int("asdf")
 
         msg = "with base 16"
-        expr = r"Pattern '{0}' not found in 'invalid literal for int\(\) with base 10: 'asdf''".format(msg)
+        expr = r"Pattern '{}' not found in 'invalid literal for int\(\) with base 10: 'asdf''".format(
+            msg
+        )
         with pytest.raises(AssertionError, match=expr):
             with pytest.raises(ValueError, match=msg):
-                int('asdf', base=10)
+                int("asdf", base=10)
+
+    def test_raises_match_wrong_type(self):
+        """Raising an exception with the wrong type and match= given.
+
+        pytest should throw the unexpected exception - the pattern match is not
+        really relevant if we got a different exception.
+        """
+        with pytest.raises(ValueError):
+            with pytest.raises(IndexError, match="nomatch"):
+                int("asdf")
+
+    def test_raises_exception_looks_iterable(self):
+        from six import add_metaclass
+
+        class Meta(type(object)):
+
+            def __getitem__(self, item):
+                return 1 / 0
+
+            def __len__(self):
+                return 1
+
+        @add_metaclass(Meta)
+        class ClassLooksIterableException(Exception):
+            pass
+
+        with pytest.raises(
+            Failed, match="DID NOT RAISE <class 'raises.ClassLooksIterableException'>"
+        ):
+            pytest.raises(ClassLooksIterableException, lambda: None)
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/python/setup_only.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/python/setup_only.py
@@ -1,243 +1,269 @@
 import pytest
 
 
-@pytest.fixture(params=['--setup-only', '--setup-plan', '--setup-show'],
-                scope='module')
+@pytest.fixture(params=["--setup-only", "--setup-plan", "--setup-show"], scope="module")
 def mode(request):
     return request.param
 
 
 def test_show_only_active_fixtures(testdir, mode):
-    p = testdir.makepyfile('''
+    p = testdir.makepyfile(
+        '''
         import pytest
         @pytest.fixture
         def _arg0():
             """hidden arg0 fixture"""
         @pytest.fixture
         def arg1():
             """arg1 docstring"""
         def test_arg1(arg1):
             pass
-    ''')
+    '''
+    )
 
     result = testdir.runpytest(mode, p)
     assert result.ret == 0
 
-    result.stdout.fnmatch_lines([
-        '*SETUP    F arg1*',
-        '*test_arg1 (fixtures used: arg1)*',
-        '*TEARDOWN F arg1*',
-    ])
+    result.stdout.fnmatch_lines(
+        ["*SETUP    F arg1*", "*test_arg1 (fixtures used: arg1)*", "*TEARDOWN F arg1*"]
+    )
     assert "_arg0" not in result.stdout.str()
 
 
 def test_show_different_scopes(testdir, mode):
-    p = testdir.makepyfile('''
+    p = testdir.makepyfile(
+        '''
         import pytest
         @pytest.fixture
         def arg_function():
             """function scoped fixture"""
         @pytest.fixture(scope='session')
         def arg_session():
             """session scoped fixture"""
         def test_arg1(arg_session, arg_function):
             pass
-    ''')
+    '''
+    )
 
     result = testdir.runpytest(mode, p)
     assert result.ret == 0
 
-    result.stdout.fnmatch_lines([
-        'SETUP    S arg_session*',
-        '*SETUP    F arg_function*',
-        '*test_arg1 (fixtures used: arg_function, arg_session)*',
-        '*TEARDOWN F arg_function*',
-        'TEARDOWN S arg_session*',
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "SETUP    S arg_session*",
+            "*SETUP    F arg_function*",
+            "*test_arg1 (fixtures used: arg_function, arg_session)*",
+            "*TEARDOWN F arg_function*",
+            "TEARDOWN S arg_session*",
+        ]
+    )
 
 
 def test_show_nested_fixtures(testdir, mode):
-    testdir.makeconftest('''
+    testdir.makeconftest(
+        '''
         import pytest
         @pytest.fixture(scope='session')
         def arg_same():
             """session scoped fixture"""
-        ''')
-    p = testdir.makepyfile('''
+        '''
+    )
+    p = testdir.makepyfile(
+        '''
         import pytest
         @pytest.fixture(scope='function')
         def arg_same(arg_same):
             """function scoped fixture"""
         def test_arg1(arg_same):
             pass
-    ''')
+    '''
+    )
 
     result = testdir.runpytest(mode, p)
     assert result.ret == 0
 
-    result.stdout.fnmatch_lines([
-        'SETUP    S arg_same*',
-        '*SETUP    F arg_same (fixtures used: arg_same)*',
-        '*test_arg1 (fixtures used: arg_same)*',
-        '*TEARDOWN F arg_same*',
-        'TEARDOWN S arg_same*',
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "SETUP    S arg_same*",
+            "*SETUP    F arg_same (fixtures used: arg_same)*",
+            "*test_arg1 (fixtures used: arg_same)*",
+            "*TEARDOWN F arg_same*",
+            "TEARDOWN S arg_same*",
+        ]
+    )
 
 
 def test_show_fixtures_with_autouse(testdir, mode):
-    p = testdir.makepyfile('''
+    p = testdir.makepyfile(
+        '''
         import pytest
         @pytest.fixture
         def arg_function():
             """function scoped fixture"""
         @pytest.fixture(scope='session', autouse=True)
         def arg_session():
             """session scoped fixture"""
         def test_arg1(arg_function):
             pass
-    ''')
+    '''
+    )
 
     result = testdir.runpytest(mode, p)
     assert result.ret == 0
 
-    result.stdout.fnmatch_lines([
-        'SETUP    S arg_session*',
-        '*SETUP    F arg_function*',
-        '*test_arg1 (fixtures used: arg_function, arg_session)*',
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "SETUP    S arg_session*",
+            "*SETUP    F arg_function*",
+            "*test_arg1 (fixtures used: arg_function, arg_session)*",
+        ]
+    )
 
 
 def test_show_fixtures_with_parameters(testdir, mode):
-    testdir.makeconftest('''
+    testdir.makeconftest(
+        '''
         import pytest
         @pytest.fixture(scope='session', params=['foo', 'bar'])
         def arg_same():
             """session scoped fixture"""
-        ''')
-    p = testdir.makepyfile('''
+        '''
+    )
+    p = testdir.makepyfile(
+        '''
         import pytest
         @pytest.fixture(scope='function')
         def arg_other(arg_same):
             """function scoped fixture"""
         def test_arg1(arg_other):
             pass
-    ''')
+    '''
+    )
 
     result = testdir.runpytest(mode, p)
     assert result.ret == 0
 
-    result.stdout.fnmatch_lines([
-        'SETUP    S arg_same?foo?',
-        'TEARDOWN S arg_same?foo?',
-        'SETUP    S arg_same?bar?',
-        'TEARDOWN S arg_same?bar?',
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "SETUP    S arg_same?foo?",
+            "TEARDOWN S arg_same?foo?",
+            "SETUP    S arg_same?bar?",
+            "TEARDOWN S arg_same?bar?",
+        ]
+    )
 
 
 def test_show_fixtures_with_parameter_ids(testdir, mode):
-    testdir.makeconftest('''
+    testdir.makeconftest(
+        '''
         import pytest
         @pytest.fixture(
             scope='session', params=['foo', 'bar'], ids=['spam', 'ham'])
         def arg_same():
             """session scoped fixture"""
-        ''')
-    p = testdir.makepyfile('''
+        '''
+    )
+    p = testdir.makepyfile(
+        '''
         import pytest
         @pytest.fixture(scope='function')
         def arg_other(arg_same):
             """function scoped fixture"""
         def test_arg1(arg_other):
             pass
-    ''')
+    '''
+    )
 
     result = testdir.runpytest(mode, p)
     assert result.ret == 0
 
-    result.stdout.fnmatch_lines([
-        'SETUP    S arg_same?spam?',
-        'SETUP    S arg_same?ham?',
-    ])
+    result.stdout.fnmatch_lines(
+        ["SETUP    S arg_same?spam?", "SETUP    S arg_same?ham?"]
+    )
 
 
 def test_show_fixtures_with_parameter_ids_function(testdir, mode):
-    p = testdir.makepyfile('''
+    p = testdir.makepyfile(
+        """
         import pytest
         @pytest.fixture(params=['foo', 'bar'], ids=lambda p: p.upper())
         def foobar():
             pass
         def test_foobar(foobar):
             pass
-    ''')
+    """
+    )
 
     result = testdir.runpytest(mode, p)
     assert result.ret == 0
 
-    result.stdout.fnmatch_lines([
-        '*SETUP    F foobar?FOO?',
-        '*SETUP    F foobar?BAR?',
-    ])
+    result.stdout.fnmatch_lines(["*SETUP    F foobar?FOO?", "*SETUP    F foobar?BAR?"])
 
 
 def test_dynamic_fixture_request(testdir):
-    p = testdir.makepyfile('''
+    p = testdir.makepyfile(
+        """
         import pytest
         @pytest.fixture()
         def dynamically_requested_fixture():
             pass
         @pytest.fixture()
         def dependent_fixture(request):
             request.getfixturevalue('dynamically_requested_fixture')
         def test_dyn(dependent_fixture):
             pass
-    ''')
+    """
+    )
 
-    result = testdir.runpytest('--setup-only', p)
+    result = testdir.runpytest("--setup-only", p)
     assert result.ret == 0
 
-    result.stdout.fnmatch_lines([
-        '*SETUP    F dynamically_requested_fixture',
-        '*TEARDOWN F dynamically_requested_fixture'
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*SETUP    F dynamically_requested_fixture",
+            "*TEARDOWN F dynamically_requested_fixture",
+        ]
+    )
 
 
 def test_capturing(testdir):
-    p = testdir.makepyfile('''
+    p = testdir.makepyfile(
+        """
         import pytest, sys
         @pytest.fixture()
         def one():
             sys.stdout.write('this should be captured')
             sys.stderr.write('this should also be captured')
         @pytest.fixture()
         def two(one):
             assert 0
         def test_capturing(two):
             pass
-    ''')
+    """
+    )
 
-    result = testdir.runpytest('--setup-only', p)
-    result.stdout.fnmatch_lines([
-        'this should be captured',
-        'this should also be captured'
-    ])
+    result = testdir.runpytest("--setup-only", p)
+    result.stdout.fnmatch_lines(
+        ["this should be captured", "this should also be captured"]
+    )
 
 
 def test_show_fixtures_and_execute_test(testdir):
     """ Verifies that setups are shown and tests are executed. """
-    p = testdir.makepyfile('''
+    p = testdir.makepyfile(
+        """
         import pytest
         @pytest.fixture
         def arg():
             assert True
         def test_arg(arg):
             assert False
-    ''')
+    """
+    )
 
     result = testdir.runpytest("--setup-show", p)
     assert result.ret == 1
 
-    result.stdout.fnmatch_lines([
-        '*SETUP    F arg*',
-        '*test_arg (fixtures used: arg)F*',
-        '*TEARDOWN F arg*',
-    ])
+    result.stdout.fnmatch_lines(
+        ["*SETUP    F arg*", "*test_arg (fixtures used: arg)F*", "*TEARDOWN F arg*"]
+    )
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/python/setup_plan.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/python/setup_plan.py
@@ -1,19 +1,19 @@
 def test_show_fixtures_and_test(testdir):
     """ Verifies that fixtures are not executed. """
-    p = testdir.makepyfile('''
+    p = testdir.makepyfile(
+        """
         import pytest
         @pytest.fixture
         def arg():
             assert False
         def test_arg(arg):
             assert False
-    ''')
+    """
+    )
 
     result = testdir.runpytest("--setup-plan", p)
     assert result.ret == 0
 
-    result.stdout.fnmatch_lines([
-        '*SETUP    F arg*',
-        '*test_arg (fixtures used: arg)',
-        '*TEARDOWN F arg*',
-    ])
+    result.stdout.fnmatch_lines(
+        ["*SETUP    F arg*", "*test_arg (fixtures used: arg)", "*TEARDOWN F arg*"]
+    )
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/python/show_fixtures_per_test.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/python/show_fixtures_per_test.py
@@ -1,158 +1,183 @@
 # -*- coding: utf-8 -*-
 
 
 def test_no_items_should_not_show_output(testdir):
-    result = testdir.runpytest('--fixtures-per-test')
-    assert 'fixtures used by' not in result.stdout.str()
+    result = testdir.runpytest("--fixtures-per-test")
+    assert "fixtures used by" not in result.stdout.str()
     assert result.ret == 0
 
 
 def test_fixtures_in_module(testdir):
-    p = testdir.makepyfile('''
+    p = testdir.makepyfile(
+        '''
         import pytest
         @pytest.fixture
         def _arg0():
             """hidden arg0 fixture"""
         @pytest.fixture
         def arg1():
             """arg1 docstring"""
         def test_arg1(arg1):
             pass
-    ''')
+    '''
+    )
 
     result = testdir.runpytest("--fixtures-per-test", p)
     assert result.ret == 0
 
-    result.stdout.fnmatch_lines([
-        '*fixtures used by test_arg1*',
-        '*(test_fixtures_in_module.py:9)*',
-        'arg1',
-        '    arg1 docstring',
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*fixtures used by test_arg1*",
+            "*(test_fixtures_in_module.py:9)*",
+            "arg1",
+            "    arg1 docstring",
+        ]
+    )
     assert "_arg0" not in result.stdout.str()
 
 
 def test_fixtures_in_conftest(testdir):
-    testdir.makeconftest('''
+    testdir.makeconftest(
+        '''
         import pytest
         @pytest.fixture
         def arg1():
             """arg1 docstring"""
         @pytest.fixture
         def arg2():
             """arg2 docstring"""
         @pytest.fixture
         def arg3(arg1, arg2):
             """arg3
             docstring
             """
-    ''')
-    p = testdir.makepyfile('''
+    '''
+    )
+    p = testdir.makepyfile(
+        """
         def test_arg2(arg2):
             pass
         def test_arg3(arg3):
             pass
-    ''')
+    """
+    )
     result = testdir.runpytest("--fixtures-per-test", p)
     assert result.ret == 0
 
-    result.stdout.fnmatch_lines([
-        '*fixtures used by test_arg2*',
-        '*(test_fixtures_in_conftest.py:2)*',
-        'arg2',
-        '    arg2 docstring',
-        '*fixtures used by test_arg3*',
-        '*(test_fixtures_in_conftest.py:4)*',
-        'arg1',
-        '    arg1 docstring',
-        'arg2',
-        '    arg2 docstring',
-        'arg3',
-        '    arg3',
-        '    docstring',
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*fixtures used by test_arg2*",
+            "*(test_fixtures_in_conftest.py:2)*",
+            "arg2",
+            "    arg2 docstring",
+            "*fixtures used by test_arg3*",
+            "*(test_fixtures_in_conftest.py:4)*",
+            "arg1",
+            "    arg1 docstring",
+            "arg2",
+            "    arg2 docstring",
+            "arg3",
+            "    arg3",
+            "    docstring",
+        ]
+    )
 
 
 def test_should_show_fixtures_used_by_test(testdir):
-    testdir.makeconftest('''
+    testdir.makeconftest(
+        '''
         import pytest
         @pytest.fixture
         def arg1():
             """arg1 from conftest"""
         @pytest.fixture
         def arg2():
             """arg2 from conftest"""
-    ''')
-    p = testdir.makepyfile('''
+    '''
+    )
+    p = testdir.makepyfile(
+        '''
         import pytest
         @pytest.fixture
         def arg1():
             """arg1 from testmodule"""
         def test_args(arg1, arg2):
             pass
-    ''')
+    '''
+    )
     result = testdir.runpytest("--fixtures-per-test", p)
     assert result.ret == 0
 
-    result.stdout.fnmatch_lines([
-        '*fixtures used by test_args*',
-        '*(test_should_show_fixtures_used_by_test.py:6)*',
-        'arg1',
-        '    arg1 from testmodule',
-        'arg2',
-        '    arg2 from conftest',
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*fixtures used by test_args*",
+            "*(test_should_show_fixtures_used_by_test.py:6)*",
+            "arg1",
+            "    arg1 from testmodule",
+            "arg2",
+            "    arg2 from conftest",
+        ]
+    )
 
 
 def test_verbose_include_private_fixtures_and_loc(testdir):
-    testdir.makeconftest('''
+    testdir.makeconftest(
+        '''
         import pytest
         @pytest.fixture
         def _arg1():
             """_arg1 from conftest"""
         @pytest.fixture
         def arg2(_arg1):
             """arg2 from conftest"""
-    ''')
-    p = testdir.makepyfile('''
+    '''
+    )
+    p = testdir.makepyfile(
+        '''
         import pytest
         @pytest.fixture
         def arg3():
             """arg3 from testmodule"""
         def test_args(arg2, arg3):
             pass
-    ''')
+    '''
+    )
     result = testdir.runpytest("--fixtures-per-test", "-v", p)
     assert result.ret == 0
 
-    result.stdout.fnmatch_lines([
-        '*fixtures used by test_args*',
-        '*(test_verbose_include_private_fixtures_and_loc.py:6)*',
-        '_arg1 -- conftest.py:3',
-        '    _arg1 from conftest',
-        'arg2 -- conftest.py:6',
-        '    arg2 from conftest',
-        'arg3 -- test_verbose_include_private_fixtures_and_loc.py:3',
-        '    arg3 from testmodule',
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*fixtures used by test_args*",
+            "*(test_verbose_include_private_fixtures_and_loc.py:6)*",
+            "_arg1 -- conftest.py:3",
+            "    _arg1 from conftest",
+            "arg2 -- conftest.py:6",
+            "    arg2 from conftest",
+            "arg3 -- test_verbose_include_private_fixtures_and_loc.py:3",
+            "    arg3 from testmodule",
+        ]
+    )
 
 
 def test_doctest_items(testdir):
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        '''
         def foo():
             """
             >>> 1 + 1
             2
             """
-    ''')
-    testdir.maketxtfile('''
+    '''
+    )
+    testdir.maketxtfile(
+        """
         >>> 1 + 1
         2
-    ''')
-    result = testdir.runpytest("--fixtures-per-test", "--doctest-modules",
-                               "--doctest-glob=*.txt", "-v")
+    """
+    )
+    result = testdir.runpytest(
+        "--fixtures-per-test", "--doctest-modules", "--doctest-glob=*.txt", "-v"
+    )
     assert result.ret == 0
 
-    result.stdout.fnmatch_lines([
-        '*collected 2 items*',
-    ])
+    result.stdout.fnmatch_lines(["*collected 2 items*"])
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/python/test_deprecations.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/python/test_deprecations.py
@@ -13,10 +13,10 @@ class PyCollectorMock(PyCollector):
         """hack to disable the actual behaviour"""
         self.called = True
 
 
 def test_pycollector_makeitem_is_deprecated():
 
     collector = PyCollectorMock()
     with pytest.deprecated_call():
-        collector.makeitem('foo', 'bar')
+        collector.makeitem("foo", "bar")
     assert collector.called
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_argcomplete.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_argcomplete.py
@@ -1,97 +1,109 @@
 from __future__ import absolute_import, division, print_function
-import py
+import subprocess
+import sys
 import pytest
 
 # test for _argcomplete but not specific for any application
 
 
 def equal_with_bash(prefix, ffc, fc, out=None):
     res = ffc(prefix)
     res_bash = set(fc(prefix))
     retval = set(res) == res_bash
     if out:
-        out.write('equal_with_bash %s %s\n' % (retval, res))
+        out.write("equal_with_bash %s %s\n" % (retval, res))
         if not retval:
-            out.write(' python - bash: %s\n' % (set(res) - res_bash))
-            out.write(' bash - python: %s\n' % (res_bash - set(res)))
+            out.write(" python - bash: %s\n" % (set(res) - res_bash))
+            out.write(" bash - python: %s\n" % (res_bash - set(res)))
     return retval
 
+
 # copied from argcomplete.completers as import from there
 # also pulls in argcomplete.__init__ which opens filedescriptor 9
 # this gives an IOError at the end of testrun
 
 
 def _wrapcall(*args, **kargs):
     try:
-        if py.std.sys.version_info > (2, 7):
-            return py.std.subprocess.check_output(*args, **kargs).decode().splitlines()
-        if 'stdout' in kargs:
-            raise ValueError('stdout argument not allowed, it will be overridden.')
-        process = py.std.subprocess.Popen(
-            stdout=py.std.subprocess.PIPE, *args, **kargs)
+        if sys.version_info > (2, 7):
+            return subprocess.check_output(*args, **kargs).decode().splitlines()
+        if "stdout" in kargs:
+            raise ValueError("stdout argument not allowed, it will be overridden.")
+        process = subprocess.Popen(stdout=subprocess.PIPE, *args, **kargs)
         output, unused_err = process.communicate()
         retcode = process.poll()
         if retcode:
             cmd = kargs.get("args")
             if cmd is None:
                 cmd = args[0]
-            raise py.std.subprocess.CalledProcessError(retcode, cmd)
+            raise subprocess.CalledProcessError(retcode, cmd)
         return output.decode().splitlines()
-    except py.std.subprocess.CalledProcessError:
+    except subprocess.CalledProcessError:
         return []
 
 
 class FilesCompleter(object):
-    'File completer class, optionally takes a list of allowed extensions'
+    "File completer class, optionally takes a list of allowed extensions"
 
     def __init__(self, allowednames=(), directories=True):
         # Fix if someone passes in a string instead of a list
         if type(allowednames) is str:
             allowednames = [allowednames]
 
-        self.allowednames = [x.lstrip('*').lstrip('.') for x in allowednames]
+        self.allowednames = [x.lstrip("*").lstrip(".") for x in allowednames]
         self.directories = directories
 
     def __call__(self, prefix, **kwargs):
         completion = []
         if self.allowednames:
             if self.directories:
-                files = _wrapcall(['bash', '-c',
-                                   "compgen -A directory -- '{p}'".format(p=prefix)])
-                completion += [f + '/' for f in files]
+                files = _wrapcall(
+                    ["bash", "-c", "compgen -A directory -- '{p}'".format(p=prefix)]
+                )
+                completion += [f + "/" for f in files]
             for x in self.allowednames:
-                completion += _wrapcall(['bash', '-c',
-                                         "compgen -A file -X '!*.{0}' -- '{p}'".format(x, p=prefix)])
+                completion += _wrapcall(
+                    [
+                        "bash",
+                        "-c",
+                        "compgen -A file -X '!*.{0}' -- '{p}'".format(x, p=prefix),
+                    ]
+                )
         else:
-            completion += _wrapcall(['bash', '-c',
-                                     "compgen -A file -- '{p}'".format(p=prefix)])
+            completion += _wrapcall(
+                ["bash", "-c", "compgen -A file -- '{p}'".format(p=prefix)]
+            )
 
-            anticomp = _wrapcall(['bash', '-c',
-                                  "compgen -A directory -- '{p}'".format(p=prefix)])
+            anticomp = _wrapcall(
+                ["bash", "-c", "compgen -A directory -- '{p}'".format(p=prefix)]
+            )
 
             completion = list(set(completion) - set(anticomp))
 
             if self.directories:
-                completion += [f + '/' for f in anticomp]
+                completion += [f + "/" for f in anticomp]
         return completion
 
 
 class TestArgComplete(object):
+
     @pytest.mark.skipif("sys.platform in ('win32', 'darwin')")
     def test_compare_with_compgen(self):
         from _pytest._argcomplete import FastFilesCompleter
+
         ffc = FastFilesCompleter()
         fc = FilesCompleter()
-        for x in ['/', '/d', '/data', 'qqq', '']:
-            assert equal_with_bash(x, ffc, fc, out=py.std.sys.stdout)
+        for x in ["/", "/d", "/data", "qqq", ""]:
+            assert equal_with_bash(x, ffc, fc, out=sys.stdout)
 
     @pytest.mark.skipif("sys.platform in ('win32', 'darwin')")
     def test_remove_dir_prefix(self):
         """this is not compatible with compgen but it is with bash itself:
         ls /usr/<TAB>
         """
         from _pytest._argcomplete import FastFilesCompleter
+
         ffc = FastFilesCompleter()
         fc = FilesCompleter()
-        for x in '/usr/'.split():
-            assert not equal_with_bash(x, ffc, fc, out=py.std.sys.stdout)
+        for x in "/usr/".split():
+            assert not equal_with_bash(x, ffc, fc, out=sys.stdout)
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_assertion.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_assertion.py
@@ -14,171 +14,173 @@ PY3 = sys.version_info >= (3, 0)
 
 @pytest.fixture
 def mock_config():
 
     class Config(object):
         verbose = False
 
         def getoption(self, name):
-            if name == 'verbose':
+            if name == "verbose":
                 return self.verbose
-            raise KeyError('Not mocked out: %s' % name)
+            raise KeyError("Not mocked out: %s" % name)
 
     return Config()
 
 
 class TestImportHookInstallation(object):
 
-    @pytest.mark.parametrize('initial_conftest', [True, False])
-    @pytest.mark.parametrize('mode', ['plain', 'rewrite'])
+    @pytest.mark.parametrize("initial_conftest", [True, False])
+    @pytest.mark.parametrize("mode", ["plain", "rewrite"])
     def test_conftest_assertion_rewrite(self, testdir, initial_conftest, mode):
         """Test that conftest files are using assertion rewrite on import.
         (#1619)
         """
-        testdir.tmpdir.join('foo/tests').ensure(dir=1)
-        conftest_path = 'conftest.py' if initial_conftest else 'foo/conftest.py'
+        testdir.tmpdir.join("foo/tests").ensure(dir=1)
+        conftest_path = "conftest.py" if initial_conftest else "foo/conftest.py"
         contents = {
             conftest_path: """
                 import pytest
                 @pytest.fixture
                 def check_first():
                     def check(values, value):
                         assert values.pop(0) == value
                     return check
             """,
-            'foo/tests/test_foo.py': """
+            "foo/tests/test_foo.py": """
                 def test(check_first):
                     check_first([10, 30], 30)
-            """
+            """,
         }
         testdir.makepyfile(**contents)
-        result = testdir.runpytest_subprocess('--assert=%s' % mode)
-        if mode == 'plain':
-            expected = 'E       AssertionError'
-        elif mode == 'rewrite':
-            expected = '*assert 10 == 30*'
+        result = testdir.runpytest_subprocess("--assert=%s" % mode)
+        if mode == "plain":
+            expected = "E       AssertionError"
+        elif mode == "rewrite":
+            expected = "*assert 10 == 30*"
         else:
             assert 0
         result.stdout.fnmatch_lines([expected])
 
     def test_rewrite_assertions_pytester_plugin(self, testdir):
         """
         Assertions in the pytester plugin must also benefit from assertion
         rewriting (#1920).
         """
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             pytest_plugins = ['pytester']
             def test_dummy_failure(testdir):  # how meta!
                 testdir.makepyfile('def test(): assert 0')
                 r = testdir.inline_run()
                 r.assertoutcome(passed=1)
-        """)
+        """
+        )
         result = testdir.runpytest_subprocess()
-        result.stdout.fnmatch_lines([
-            '*assert 1 == 0*',
-        ])
+        result.stdout.fnmatch_lines(["*assert 1 == 0*"])
 
-    @pytest.mark.parametrize('mode', ['plain', 'rewrite'])
+    @pytest.mark.parametrize("mode", ["plain", "rewrite"])
     def test_pytest_plugins_rewrite(self, testdir, mode):
         contents = {
-            'conftest.py': """
+            "conftest.py": """
                 pytest_plugins = ['ham']
             """,
-            'ham.py': """
+            "ham.py": """
                 import pytest
                 @pytest.fixture
                 def check_first():
                     def check(values, value):
                         assert values.pop(0) == value
                     return check
             """,
-            'test_foo.py': """
+            "test_foo.py": """
                 def test_foo(check_first):
                     check_first([10, 30], 30)
             """,
         }
         testdir.makepyfile(**contents)
-        result = testdir.runpytest_subprocess('--assert=%s' % mode)
-        if mode == 'plain':
-            expected = 'E       AssertionError'
-        elif mode == 'rewrite':
-            expected = '*assert 10 == 30*'
+        result = testdir.runpytest_subprocess("--assert=%s" % mode)
+        if mode == "plain":
+            expected = "E       AssertionError"
+        elif mode == "rewrite":
+            expected = "*assert 10 == 30*"
         else:
             assert 0
         result.stdout.fnmatch_lines([expected])
 
-    @pytest.mark.parametrize('mode', ['str', 'list'])
+    @pytest.mark.parametrize("mode", ["str", "list"])
     def test_pytest_plugins_rewrite_module_names(self, testdir, mode):
         """Test that pluginmanager correct marks pytest_plugins variables
         for assertion rewriting if they are defined as plain strings or
         list of strings (#1888).
         """
-        plugins = '"ham"' if mode == 'str' else '["ham"]'
+        plugins = '"ham"' if mode == "str" else '["ham"]'
         contents = {
-            'conftest.py': """
+            "conftest.py": """
                 pytest_plugins = {plugins}
-            """.format(plugins=plugins),
-            'ham.py': """
+            """.format(
+                plugins=plugins
+            ),
+            "ham.py": """
                 import pytest
             """,
-            'test_foo.py': """
+            "test_foo.py": """
                 def test_foo(pytestconfig):
                     assert 'ham' in pytestconfig.pluginmanager.rewrite_hook._must_rewrite
             """,
         }
         testdir.makepyfile(**contents)
-        result = testdir.runpytest_subprocess('--assert=rewrite')
+        result = testdir.runpytest_subprocess("--assert=rewrite")
         assert result.ret == 0
 
     def test_pytest_plugins_rewrite_module_names_correctly(self, testdir):
         """Test that we match files correctly when they are marked for rewriting (#2939)."""
         contents = {
-            'conftest.py': """
+            "conftest.py": """
                 pytest_plugins = "ham"
             """,
-            'ham.py': "",
-            'hamster.py': "",
-            'test_foo.py': """
+            "ham.py": "",
+            "hamster.py": "",
+            "test_foo.py": """
                 def test_foo(pytestconfig):
                     assert pytestconfig.pluginmanager.rewrite_hook.find_module('ham') is not None
                     assert pytestconfig.pluginmanager.rewrite_hook.find_module('hamster') is None
             """,
         }
         testdir.makepyfile(**contents)
-        result = testdir.runpytest_subprocess('--assert=rewrite')
+        result = testdir.runpytest_subprocess("--assert=rewrite")
         assert result.ret == 0
 
-    @pytest.mark.parametrize('mode', ['plain', 'rewrite'])
-    @pytest.mark.parametrize('plugin_state', ['development', 'installed'])
+    @pytest.mark.parametrize("mode", ["plain", "rewrite"])
+    @pytest.mark.parametrize("plugin_state", ["development", "installed"])
     def test_installed_plugin_rewrite(self, testdir, mode, plugin_state):
         # Make sure the hook is installed early enough so that plugins
         # installed via setuptools are rewritten.
-        testdir.tmpdir.join('hampkg').ensure(dir=1)
+        testdir.tmpdir.join("hampkg").ensure(dir=1)
         contents = {
-            'hampkg/__init__.py': """
+            "hampkg/__init__.py": """
                 import pytest
 
                 @pytest.fixture
                 def check_first2():
                     def check(values, value):
                         assert values.pop(0) == value
                     return check
             """,
-            'spamplugin.py': """
+            "spamplugin.py": """
             import pytest
             from hampkg import check_first2
 
             @pytest.fixture
             def check_first():
                 def check(values, value):
                     assert values.pop(0) == value
                 return check
             """,
-            'mainwrapper.py': """
+            "mainwrapper.py": """
             import pytest, pkg_resources
 
             plugin_state = "{plugin_state}"
 
             class DummyDistInfo(object):
                 project_name = 'spam'
                 version = '1.0'
 
@@ -204,241 +206,265 @@ class TestImportHookInstallation(object)
                     import spamplugin
                     return spamplugin
 
             def iter_entry_points(name):
                 yield DummyEntryPoint()
 
             pkg_resources.iter_entry_points = iter_entry_points
             pytest.main()
-            """.format(plugin_state=plugin_state),
-            'test_foo.py': """
+            """.format(
+                plugin_state=plugin_state
+            ),
+            "test_foo.py": """
             def test(check_first):
                 check_first([10, 30], 30)
 
             def test2(check_first2):
                 check_first([10, 30], 30)
             """,
         }
         testdir.makepyfile(**contents)
-        result = testdir.run(sys.executable, 'mainwrapper.py', '-s', '--assert=%s' % mode)
-        if mode == 'plain':
-            expected = 'E       AssertionError'
-        elif mode == 'rewrite':
-            expected = '*assert 10 == 30*'
+        result = testdir.run(
+            sys.executable, "mainwrapper.py", "-s", "--assert=%s" % mode
+        )
+        if mode == "plain":
+            expected = "E       AssertionError"
+        elif mode == "rewrite":
+            expected = "*assert 10 == 30*"
         else:
             assert 0
         result.stdout.fnmatch_lines([expected])
 
     def test_rewrite_ast(self, testdir):
-        testdir.tmpdir.join('pkg').ensure(dir=1)
+        testdir.tmpdir.join("pkg").ensure(dir=1)
         contents = {
-            'pkg/__init__.py': """
+            "pkg/__init__.py": """
                 import pytest
                 pytest.register_assert_rewrite('pkg.helper')
             """,
-            'pkg/helper.py': """
+            "pkg/helper.py": """
                 def tool():
                     a, b = 2, 3
                     assert a == b
             """,
-            'pkg/plugin.py': """
+            "pkg/plugin.py": """
                 import pytest, pkg.helper
                 @pytest.fixture
                 def tool():
                     return pkg.helper.tool
             """,
-            'pkg/other.py': """
+            "pkg/other.py": """
                 values = [3, 2]
                 def tool():
                     assert values.pop() == 3
             """,
-            'conftest.py': """
+            "conftest.py": """
                 pytest_plugins = ['pkg.plugin']
             """,
-            'test_pkg.py': """
+            "test_pkg.py": """
                 import pkg.other
                 def test_tool(tool):
                     tool()
                 def test_other():
                     pkg.other.tool()
             """,
         }
         testdir.makepyfile(**contents)
-        result = testdir.runpytest_subprocess('--assert=rewrite')
-        result.stdout.fnmatch_lines(['>*assert a == b*',
-                                     'E*assert 2 == 3*',
-                                     '>*assert values.pop() == 3*',
-                                     'E*AssertionError'])
+        result = testdir.runpytest_subprocess("--assert=rewrite")
+        result.stdout.fnmatch_lines(
+            [
+                ">*assert a == b*",
+                "E*assert 2 == 3*",
+                ">*assert values.pop() == 3*",
+                "E*AssertionError",
+            ]
+        )
 
     def test_register_assert_rewrite_checks_types(self):
         with pytest.raises(TypeError):
-            pytest.register_assert_rewrite(['pytest_tests_internal_non_existing'])
-        pytest.register_assert_rewrite('pytest_tests_internal_non_existing',
-                                       'pytest_tests_internal_non_existing2')
+            pytest.register_assert_rewrite(["pytest_tests_internal_non_existing"])
+        pytest.register_assert_rewrite(
+            "pytest_tests_internal_non_existing", "pytest_tests_internal_non_existing2"
+        )
 
 
 class TestBinReprIntegration(object):
 
     def test_pytest_assertrepr_compare_called(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             values = []
             def pytest_assertrepr_compare(op, left, right):
                 values.append((op, left, right))
 
             @pytest.fixture
             def list(request):
                 return values
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             def test_hello():
                 assert 0 == 1
             def test_check(list):
                 assert list == [("==", 0, 1)]
-        """)
+        """
+        )
         result = testdir.runpytest("-v")
-        result.stdout.fnmatch_lines([
-            "*test_hello*FAIL*",
-            "*test_check*PASS*",
-        ])
+        result.stdout.fnmatch_lines(["*test_hello*FAIL*", "*test_check*PASS*"])
 
 
 def callequal(left, right, verbose=False):
     config = mock_config()
     config.verbose = verbose
-    return plugin.pytest_assertrepr_compare(config, '==', left, right)
+    return plugin.pytest_assertrepr_compare(config, "==", left, right)
 
 
 class TestAssert_reprcompare(object):
+
     def test_different_types(self):
-        assert callequal([0, 1], 'foo') is None
+        assert callequal([0, 1], "foo") is None
 
     def test_summary(self):
         summary = callequal([0, 1], [0, 2])[0]
         assert len(summary) < 65
 
     def test_text_diff(self):
-        diff = callequal('spam', 'eggs')[1:]
-        assert '- spam' in diff
-        assert '+ eggs' in diff
+        diff = callequal("spam", "eggs")[1:]
+        assert "- spam" in diff
+        assert "+ eggs" in diff
 
     def test_text_skipping(self):
-        lines = callequal('a' * 50 + 'spam', 'a' * 50 + 'eggs')
-        assert 'Skipping' in lines[1]
+        lines = callequal("a" * 50 + "spam", "a" * 50 + "eggs")
+        assert "Skipping" in lines[1]
         for line in lines:
-            assert 'a' * 50 not in line
+            assert "a" * 50 not in line
 
     def test_text_skipping_verbose(self):
-        lines = callequal('a' * 50 + 'spam', 'a' * 50 + 'eggs', verbose=True)
-        assert '- ' + 'a' * 50 + 'spam' in lines
-        assert '+ ' + 'a' * 50 + 'eggs' in lines
+        lines = callequal("a" * 50 + "spam", "a" * 50 + "eggs", verbose=True)
+        assert "- " + "a" * 50 + "spam" in lines
+        assert "+ " + "a" * 50 + "eggs" in lines
 
     def test_multiline_text_diff(self):
-        left = 'foo\nspam\nbar'
-        right = 'foo\neggs\nbar'
+        left = "foo\nspam\nbar"
+        right = "foo\neggs\nbar"
         diff = callequal(left, right)
-        assert '- spam' in diff
-        assert '+ eggs' in diff
+        assert "- spam" in diff
+        assert "+ eggs" in diff
 
     def test_list(self):
         expl = callequal([0, 1], [0, 2])
         assert len(expl) > 1
 
     @pytest.mark.parametrize(
-        ['left', 'right', 'expected'], [
-            ([0, 1], [0, 2], """
+        ["left", "right", "expected"],
+        [
+            (
+                [0, 1],
+                [0, 2],
+                """
                 Full diff:
                 - [0, 1]
                 ?     ^
                 + [0, 2]
                 ?     ^
-            """),
-            ({0: 1}, {0: 2}, """
+            """,
+            ),
+            (
+                {0: 1},
+                {0: 2},
+                """
                 Full diff:
                 - {0: 1}
                 ?     ^
                 + {0: 2}
                 ?     ^
-            """),
-            (set([0, 1]), set([0, 2]), """
+            """,
+            ),
+            (
+                {0, 1},
+                {0, 2},
+                """
                 Full diff:
                 - set([0, 1])
                 ?         ^
                 + set([0, 2])
                 ?         ^
-            """ if not PY3 else """
+            """
+                if not PY3
+                else """
                 Full diff:
                 - {0, 1}
                 ?     ^
                 + {0, 2}
                 ?     ^
-            """)
-        ]
+            """,
+            ),
+        ],
     )
     def test_iterable_full_diff(self, left, right, expected):
         """Test the full diff assertion failure explanation.
 
         When verbose is False, then just a -v notice to get the diff is rendered,
         when verbose is True, then ndiff of the pprint is returned.
         """
         expl = callequal(left, right, verbose=False)
-        assert expl[-1] == 'Use -v to get the full diff'
-        expl = '\n'.join(callequal(left, right, verbose=True))
+        assert expl[-1] == "Use -v to get the full diff"
+        expl = "\n".join(callequal(left, right, verbose=True))
         assert expl.endswith(textwrap.dedent(expected).strip())
 
     def test_list_different_lengths(self):
         expl = callequal([0, 1], [0, 1, 2])
         assert len(expl) > 1
         expl = callequal([0, 1, 2], [0, 1])
         assert len(expl) > 1
 
     def test_dict(self):
-        expl = callequal({'a': 0}, {'a': 1})
+        expl = callequal({"a": 0}, {"a": 1})
         assert len(expl) > 1
 
     def test_dict_omitting(self):
-        lines = callequal({'a': 0, 'b': 1}, {'a': 1, 'b': 1})
-        assert lines[1].startswith('Omitting 1 identical item')
-        assert 'Common items' not in lines
+        lines = callequal({"a": 0, "b": 1}, {"a": 1, "b": 1})
+        assert lines[1].startswith("Omitting 1 identical item")
+        assert "Common items" not in lines
         for line in lines[1:]:
-            assert 'b' not in line
+            assert "b" not in line
 
     def test_dict_omitting_with_verbosity_1(self):
         """ Ensure differing items are visible for verbosity=1 (#1512) """
-        lines = callequal({'a': 0, 'b': 1}, {'a': 1, 'b': 1}, verbose=1)
-        assert lines[1].startswith('Omitting 1 identical item')
-        assert lines[2].startswith('Differing items')
+        lines = callequal({"a": 0, "b": 1}, {"a": 1, "b": 1}, verbose=1)
+        assert lines[1].startswith("Omitting 1 identical item")
+        assert lines[2].startswith("Differing items")
         assert lines[3] == "{'a': 0} != {'a': 1}"
-        assert 'Common items' not in lines
+        assert "Common items" not in lines
 
     def test_dict_omitting_with_verbosity_2(self):
-        lines = callequal({'a': 0, 'b': 1}, {'a': 1, 'b': 1}, verbose=2)
-        assert lines[1].startswith('Common items:')
-        assert 'Omitting' not in lines[1]
+        lines = callequal({"a": 0, "b": 1}, {"a": 1, "b": 1}, verbose=2)
+        assert lines[1].startswith("Common items:")
+        assert "Omitting" not in lines[1]
         assert lines[2] == "{'b': 1}"
 
     def test_set(self):
-        expl = callequal(set([0, 1]), set([0, 2]))
+        expl = callequal({0, 1}, {0, 2})
         assert len(expl) > 1
 
     def test_frozenzet(self):
-        expl = callequal(frozenset([0, 1]), set([0, 2]))
+        expl = callequal(frozenset([0, 1]), {0, 2})
         assert len(expl) > 1
 
     def test_Sequence(self):
-        col = py.builtin._tryimport(
-            "collections.abc",
-            "collections",
-            "sys")
+        col = py.builtin._tryimport("collections.abc", "collections", "sys")
         if not hasattr(col, "MutableSequence"):
             pytest.skip("cannot import MutableSequence")
         MutableSequence = col.MutableSequence
 
         class TestSequence(MutableSequence):  # works with a Sequence subclass
+
             def __init__(self, iterable):
                 self.elements = list(iterable)
 
             def __getitem__(self, item):
                 return self.elements[item]
 
             def __len__(self):
                 return len(self.elements)
@@ -457,164 +483,169 @@ class TestAssert_reprcompare(object):
 
     def test_list_tuples(self):
         expl = callequal([], [(1, 2)])
         assert len(expl) > 1
         expl = callequal([(1, 2)], [])
         assert len(expl) > 1
 
     def test_list_bad_repr(self):
+
         class A(object):
+
             def __repr__(self):
                 raise ValueError(42)
+
         expl = callequal([], [A()])
-        assert 'ValueError' in "".join(expl)
-        expl = callequal({}, {'1': A()})
-        assert 'faulty' in "".join(expl)
+        assert "ValueError" in "".join(expl)
+        expl = callequal({}, {"1": A()})
+        assert "faulty" in "".join(expl)
 
     def test_one_repr_empty(self):
         """
         the faulty empty string repr did trigger
-        a unbound local error in _diff_text
+        an unbound local error in _diff_text
         """
+
         class A(str):
+
             def __repr__(self):
-                return ''
-        expl = callequal(A(), '')
+                return ""
+
+        expl = callequal(A(), "")
         assert not expl
 
     def test_repr_no_exc(self):
-        expl = ' '.join(callequal('foo', 'bar'))
-        assert 'raised in repr()' not in expl
+        expl = " ".join(callequal("foo", "bar"))
+        assert "raised in repr()" not in expl
 
     def test_unicode(self):
-        left = py.builtin._totext('£€', 'utf-8')
-        right = py.builtin._totext('£', 'utf-8')
+        left = py.builtin._totext("£€", "utf-8")
+        right = py.builtin._totext("£", "utf-8")
         expl = callequal(left, right)
-        assert expl[0] == py.builtin._totext("'£€' == '£'", 'utf-8')
-        assert expl[1] == py.builtin._totext('- £€', 'utf-8')
-        assert expl[2] == py.builtin._totext('+ £', 'utf-8')
+        assert expl[0] == py.builtin._totext("'£€' == '£'", "utf-8")
+        assert expl[1] == py.builtin._totext("- £€", "utf-8")
+        assert expl[2] == py.builtin._totext("+ £", "utf-8")
 
     def test_nonascii_text(self):
         """
         :issue: 877
         non ascii python2 str caused a UnicodeDecodeError
         """
+
         class A(str):
+
             def __repr__(self):
-                return '\xff'
-        expl = callequal(A(), '1')
+                return "\xff"
+
+        expl = callequal(A(), "1")
         assert expl
 
     def test_format_nonascii_explanation(self):
-        assert util.format_explanation('λ')
+        assert util.format_explanation("λ")
 
     def test_mojibake(self):
         # issue 429
-        left = 'e'
-        right = '\xc3\xa9'
-        if not isinstance(left, py.builtin.bytes):
-            left = py.builtin.bytes(left, 'utf-8')
-            right = py.builtin.bytes(right, 'utf-8')
+        left = "e"
+        right = "\xc3\xa9"
+        if not isinstance(left, bytes):
+            left = bytes(left, "utf-8")
+            right = bytes(right, "utf-8")
         expl = callequal(left, right)
         for line in expl:
             assert isinstance(line, py.builtin.text)
-        msg = py.builtin._totext('\n').join(expl)
+        msg = py.builtin._totext("\n").join(expl)
         assert msg
 
 
 class TestFormatExplanation(object):
 
     def test_special_chars_full(self, testdir):
         # Issue 453, for the bug this would raise IndexError
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_foo():
                 assert '\\n}' == ''
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == 1
-        result.stdout.fnmatch_lines([
-            "*AssertionError*",
-        ])
+        result.stdout.fnmatch_lines(["*AssertionError*"])
 
     def test_fmt_simple(self):
-        expl = 'assert foo'
-        assert util.format_explanation(expl) == 'assert foo'
+        expl = "assert foo"
+        assert util.format_explanation(expl) == "assert foo"
 
     def test_fmt_where(self):
-        expl = '\n'.join(['assert 1',
-                          '{1 = foo',
-                          '} == 2'])
-        res = '\n'.join(['assert 1 == 2',
-                         ' +  where 1 = foo'])
+        expl = "\n".join(["assert 1", "{1 = foo", "} == 2"])
+        res = "\n".join(["assert 1 == 2", " +  where 1 = foo"])
         assert util.format_explanation(expl) == res
 
     def test_fmt_and(self):
-        expl = '\n'.join(['assert 1',
-                          '{1 = foo',
-                          '} == 2',
-                          '{2 = bar',
-                          '}'])
-        res = '\n'.join(['assert 1 == 2',
-                         ' +  where 1 = foo',
-                         ' +  and   2 = bar'])
+        expl = "\n".join(["assert 1", "{1 = foo", "} == 2", "{2 = bar", "}"])
+        res = "\n".join(["assert 1 == 2", " +  where 1 = foo", " +  and   2 = bar"])
         assert util.format_explanation(expl) == res
 
     def test_fmt_where_nested(self):
-        expl = '\n'.join(['assert 1',
-                          '{1 = foo',
-                          '{foo = bar',
-                          '}',
-                          '} == 2'])
-        res = '\n'.join(['assert 1 == 2',
-                         ' +  where 1 = foo',
-                         ' +    where foo = bar'])
+        expl = "\n".join(["assert 1", "{1 = foo", "{foo = bar", "}", "} == 2"])
+        res = "\n".join(["assert 1 == 2", " +  where 1 = foo", " +    where foo = bar"])
         assert util.format_explanation(expl) == res
 
     def test_fmt_newline(self):
-        expl = '\n'.join(['assert "foo" == "bar"',
-                          '~- foo',
-                          '~+ bar'])
-        res = '\n'.join(['assert "foo" == "bar"',
-                         '  - foo',
-                         '  + bar'])
+        expl = "\n".join(['assert "foo" == "bar"', "~- foo", "~+ bar"])
+        res = "\n".join(['assert "foo" == "bar"', "  - foo", "  + bar"])
         assert util.format_explanation(expl) == res
 
     def test_fmt_newline_escaped(self):
-        expl = '\n'.join(['assert foo == bar',
-                          'baz'])
-        res = 'assert foo == bar\\nbaz'
+        expl = "\n".join(["assert foo == bar", "baz"])
+        res = "assert foo == bar\\nbaz"
         assert util.format_explanation(expl) == res
 
     def test_fmt_newline_before_where(self):
-        expl = '\n'.join(['the assertion message here',
-                          '>assert 1',
-                          '{1 = foo',
-                          '} == 2',
-                          '{2 = bar',
-                          '}'])
-        res = '\n'.join(['the assertion message here',
-                         'assert 1 == 2',
-                         ' +  where 1 = foo',
-                         ' +  and   2 = bar'])
+        expl = "\n".join(
+            [
+                "the assertion message here",
+                ">assert 1",
+                "{1 = foo",
+                "} == 2",
+                "{2 = bar",
+                "}",
+            ]
+        )
+        res = "\n".join(
+            [
+                "the assertion message here",
+                "assert 1 == 2",
+                " +  where 1 = foo",
+                " +  and   2 = bar",
+            ]
+        )
         assert util.format_explanation(expl) == res
 
     def test_fmt_multi_newline_before_where(self):
-        expl = '\n'.join(['the assertion',
-                          '~message here',
-                          '>assert 1',
-                          '{1 = foo',
-                          '} == 2',
-                          '{2 = bar',
-                          '}'])
-        res = '\n'.join(['the assertion',
-                         '  message here',
-                         'assert 1 == 2',
-                         ' +  where 1 = foo',
-                         ' +  and   2 = bar'])
+        expl = "\n".join(
+            [
+                "the assertion",
+                "~message here",
+                ">assert 1",
+                "{1 = foo",
+                "} == 2",
+                "{2 = bar",
+                "}",
+            ]
+        )
+        res = "\n".join(
+            [
+                "the assertion",
+                "  message here",
+                "assert 1 == 2",
+                " +  where 1 = foo",
+                " +  and   2 = bar",
+            ]
+        )
         assert util.format_explanation(expl) == res
 
 
 class TestTruncateExplanation(object):
 
     """ Confirm assertion output is truncated as expected """
 
     # The number of lines in the truncation explanation message. Used
@@ -622,445 +653,520 @@ class TestTruncateExplanation(object):
     LINES_IN_TRUNCATION_MSG = 2
 
     def test_doesnt_truncate_when_input_is_empty_list(self):
         expl = []
         result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)
         assert result == expl
 
     def test_doesnt_truncate_at_when_input_is_5_lines_and_LT_max_chars(self):
-        expl = ['a' * 100 for x in range(5)]
+        expl = ["a" * 100 for x in range(5)]
         result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)
         assert result == expl
 
     def test_truncates_at_8_lines_when_given_list_of_empty_strings(self):
-        expl = ['' for x in range(50)]
+        expl = ["" for x in range(50)]
         result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)
         assert result != expl
         assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG
         assert "Full output truncated" in result[-1]
         assert "43 lines hidden" in result[-1]
-        last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG - 1]
+        last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
         assert last_line_before_trunc_msg.endswith("...")
 
     def test_truncates_at_8_lines_when_first_8_lines_are_LT_max_chars(self):
-        expl = ['a' for x in range(100)]
+        expl = ["a" for x in range(100)]
         result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)
         assert result != expl
         assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG
         assert "Full output truncated" in result[-1]
         assert "93 lines hidden" in result[-1]
-        last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG - 1]
+        last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
         assert last_line_before_trunc_msg.endswith("...")
 
     def test_truncates_at_8_lines_when_first_8_lines_are_EQ_max_chars(self):
-        expl = ['a' * 80 for x in range(16)]
+        expl = ["a" * 80 for x in range(16)]
         result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)
         assert result != expl
         assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG
         assert "Full output truncated" in result[-1]
         assert "9 lines hidden" in result[-1]
-        last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG - 1]
+        last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
         assert last_line_before_trunc_msg.endswith("...")
 
     def test_truncates_at_4_lines_when_first_4_lines_are_GT_max_chars(self):
-        expl = ['a' * 250 for x in range(10)]
+        expl = ["a" * 250 for x in range(10)]
         result = truncate._truncate_explanation(expl, max_lines=8, max_chars=999)
         assert result != expl
         assert len(result) == 4 + self.LINES_IN_TRUNCATION_MSG
         assert "Full output truncated" in result[-1]
         assert "7 lines hidden" in result[-1]
-        last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG - 1]
+        last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
         assert last_line_before_trunc_msg.endswith("...")
 
     def test_truncates_at_1_line_when_first_line_is_GT_max_chars(self):
-        expl = ['a' * 250 for x in range(1000)]
+        expl = ["a" * 250 for x in range(1000)]
         result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)
         assert result != expl
         assert len(result) == 1 + self.LINES_IN_TRUNCATION_MSG
         assert "Full output truncated" in result[-1]
         assert "1000 lines hidden" in result[-1]
-        last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG - 1]
+        last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]
         assert last_line_before_trunc_msg.endswith("...")
 
     def test_full_output_truncated(self, monkeypatch, testdir):
         """ Test against full runpytest() output. """
 
         line_count = 7
         line_len = 100
         expected_truncated_lines = 2
-        testdir.makepyfile(r"""
+        testdir.makepyfile(
+            r"""
             def test_many_lines():
                 a = list([str(i)[0] * %d for i in range(%d)])
                 b = a[::2]
                 a = '\n'.join(map(str, a))
                 b = '\n'.join(map(str, b))
                 assert a == b
-        """ % (line_len, line_count))
-        monkeypatch.delenv('CI', raising=False)
+        """
+            % (line_len, line_count)
+        )
+        monkeypatch.delenv("CI", raising=False)
 
         result = testdir.runpytest()
         # without -vv, truncate the message showing a few diff lines only
-        result.stdout.fnmatch_lines([
-            "*- 1*",
-            "*- 3*",
-            "*- 5*",
-            "*truncated (%d lines hidden)*use*-vv*" % expected_truncated_lines,
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*- 1*",
+                "*- 3*",
+                "*- 5*",
+                "*truncated (%d lines hidden)*use*-vv*" % expected_truncated_lines,
+            ]
+        )
 
-        result = testdir.runpytest('-vv')
-        result.stdout.fnmatch_lines([
-            "* 6*",
-        ])
+        result = testdir.runpytest("-vv")
+        result.stdout.fnmatch_lines(["* 6*"])
 
-        monkeypatch.setenv('CI', '1')
+        monkeypatch.setenv("CI", "1")
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "* 6*",
-        ])
+        result.stdout.fnmatch_lines(["* 6*"])
 
 
 def test_python25_compile_issue257(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_rewritten():
             assert 1 == 2
         # some comment
-    """)
+    """
+    )
     result = testdir.runpytest()
     assert result.ret == 1
-    result.stdout.fnmatch_lines("""
+    result.stdout.fnmatch_lines(
+        """
             *E*assert 1 == 2*
             *1 failed*
-    """)
+    """
+    )
 
 
 def test_rewritten(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_rewritten():
             assert "@py_builtins" in globals()
-    """)
+    """
+    )
     assert testdir.runpytest().ret == 0
 
 
 def test_reprcompare_notin(mock_config):
     detail = plugin.pytest_assertrepr_compare(
-        mock_config, 'not in', 'foo', 'aaafoobbb')[1:]
-    assert detail == ["'foo' is contained here:", '  aaafoobbb', '?    +++']
+        mock_config, "not in", "foo", "aaafoobbb"
+    )[
+        1:
+    ]
+    assert detail == ["'foo' is contained here:", "  aaafoobbb", "?    +++"]
+
+
+def test_reprcompare_whitespaces(mock_config):
+    detail = plugin.pytest_assertrepr_compare(mock_config, "==", "\r\n", "\n")
+    assert (
+        detail
+        == [
+            r"'\r\n' == '\n'",
+            r"Strings contain only whitespace, escaping them using repr()",
+            r"- '\r\n'",
+            r"?  --",
+            r"+ '\n'",
+        ]
+    )
 
 
 def test_pytest_assertrepr_compare_integration(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_hello():
             x = set(range(100))
             y = x.copy()
             y.remove(50)
             assert x == y
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        "*def test_hello():*",
-        "*assert x == y*",
-        "*E*Extra items*left*",
-        "*E*50*",
-    ])
+    result.stdout.fnmatch_lines(
+        ["*def test_hello():*", "*assert x == y*", "*E*Extra items*left*", "*E*50*"]
+    )
 
 
 def test_sequence_comparison_uses_repr(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_hello():
             x = set("hello x")
             y = set("hello y")
             assert x == y
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        "*def test_hello():*",
-        "*assert x == y*",
-        "*E*Extra items*left*",
-        "*E*'x'*",
-        "*E*Extra items*right*",
-        "*E*'y'*",
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*def test_hello():*",
+            "*assert x == y*",
+            "*E*Extra items*left*",
+            "*E*'x'*",
+            "*E*Extra items*right*",
+            "*E*'y'*",
+        ]
+    )
 
 
 def test_assertrepr_loaded_per_dir(testdir):
-    testdir.makepyfile(test_base=['def test_base(): assert 1 == 2'])
-    a = testdir.mkdir('a')
-    a_test = a.join('test_a.py')
-    a_test.write('def test_a(): assert 1 == 2')
-    a_conftest = a.join('conftest.py')
+    testdir.makepyfile(test_base=["def test_base(): assert 1 == 2"])
+    a = testdir.mkdir("a")
+    a_test = a.join("test_a.py")
+    a_test.write("def test_a(): assert 1 == 2")
+    a_conftest = a.join("conftest.py")
     a_conftest.write('def pytest_assertrepr_compare(): return ["summary a"]')
-    b = testdir.mkdir('b')
-    b_test = b.join('test_b.py')
-    b_test.write('def test_b(): assert 1 == 2')
-    b_conftest = b.join('conftest.py')
+    b = testdir.mkdir("b")
+    b_test = b.join("test_b.py")
+    b_test.write("def test_b(): assert 1 == 2")
+    b_conftest = b.join("conftest.py")
     b_conftest.write('def pytest_assertrepr_compare(): return ["summary b"]')
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        '*def test_base():*',
-        '*E*assert 1 == 2*',
-        '*def test_a():*',
-        '*E*assert summary a*',
-        '*def test_b():*',
-        '*E*assert summary b*'])
+    result.stdout.fnmatch_lines(
+        [
+            "*def test_base():*",
+            "*E*assert 1 == 2*",
+            "*def test_a():*",
+            "*E*assert summary a*",
+            "*def test_b():*",
+            "*E*assert summary b*",
+        ]
+    )
 
 
 def test_assertion_options(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_hello():
             x = 3
             assert x == 4
-    """)
+    """
+    )
     result = testdir.runpytest()
     assert "3 == 4" in result.stdout.str()
     result = testdir.runpytest_subprocess("--assert=plain")
     assert "3 == 4" not in result.stdout.str()
 
 
 def test_triple_quoted_string_issue113(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_hello():
             assert "" == '''
-    '''""")
+    '''"""
+    )
     result = testdir.runpytest("--fulltrace")
-    result.stdout.fnmatch_lines([
-        "*1 failed*",
-    ])
-    assert 'SyntaxError' not in result.stdout.str()
+    result.stdout.fnmatch_lines(["*1 failed*"])
+    assert "SyntaxError" not in result.stdout.str()
 
 
 def test_traceback_failure(testdir):
-    p1 = testdir.makepyfile("""
+    p1 = testdir.makepyfile(
+        """
         def g():
             return 2
         def f(x):
             assert x == g()
         def test_onefails():
             f(3)
-    """)
+    """
+    )
     result = testdir.runpytest(p1, "--tb=long")
-    result.stdout.fnmatch_lines([
-        "*test_traceback_failure.py F*",
-        "====* FAILURES *====",
-        "____*____",
-        "",
-        "    def test_onefails():",
-        ">       f(3)",
-        "",
-        "*test_*.py:6: ",
-        "_ _ _ *",
-        # "",
-        "    def f(x):",
-        ">       assert x == g()",
-        "E       assert 3 == 2",
-        "E        +  where 2 = g()",
-        "",
-        "*test_traceback_failure.py:4: AssertionError"
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*test_traceback_failure.py F*",
+            "====* FAILURES *====",
+            "____*____",
+            "",
+            "    def test_onefails():",
+            ">       f(3)",
+            "",
+            "*test_*.py:6: ",
+            "_ _ _ *",
+            # "",
+            "    def f(x):",
+            ">       assert x == g()",
+            "E       assert 3 == 2",
+            "E        +  where 2 = g()",
+            "",
+            "*test_traceback_failure.py:4: AssertionError",
+        ]
+    )
 
     result = testdir.runpytest(p1)  # "auto"
-    result.stdout.fnmatch_lines([
-        "*test_traceback_failure.py F*",
-        "====* FAILURES *====",
-        "____*____",
-        "",
-        "    def test_onefails():",
-        ">       f(3)",
-        "",
-        "*test_*.py:6: ",
-        "",
-        "    def f(x):",
-        ">       assert x == g()",
-        "E       assert 3 == 2",
-        "E        +  where 2 = g()",
-        "",
-        "*test_traceback_failure.py:4: AssertionError"
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*test_traceback_failure.py F*",
+            "====* FAILURES *====",
+            "____*____",
+            "",
+            "    def test_onefails():",
+            ">       f(3)",
+            "",
+            "*test_*.py:6: ",
+            "",
+            "    def f(x):",
+            ">       assert x == g()",
+            "E       assert 3 == 2",
+            "E        +  where 2 = g()",
+            "",
+            "*test_traceback_failure.py:4: AssertionError",
+        ]
+    )
 
 
-@pytest.mark.skipif(sys.version_info[:2] <= (3, 3), reason='Python 3.4+ shows chained exceptions on multiprocess')
+@pytest.mark.skipif(
+    sys.version_info[:2] <= (3, 3),
+    reason="Python 3.4+ shows chained exceptions on multiprocess",
+)
 def test_exception_handling_no_traceback(testdir):
     """
     Handle chain exceptions in tasks submitted by the multiprocess module (#1984).
     """
-    p1 = testdir.makepyfile("""
+    p1 = testdir.makepyfile(
+        """
         from multiprocessing import Pool
 
         def process_task(n):
             assert n == 10
 
         def multitask_job():
             tasks = [1]
             with Pool(processes=1) as pool:
                 pool.map(process_task, tasks)
 
         def test_multitask_job():
             multitask_job()
-    """)
+    """
+    )
     result = testdir.runpytest(p1, "--tb=long")
-    result.stdout.fnmatch_lines([
-        "====* FAILURES *====",
-        "*multiprocessing.pool.RemoteTraceback:*",
-        "Traceback (most recent call last):",
-        "*assert n == 10",
-        "The above exception was the direct cause of the following exception:",
-        "> * multitask_job()",
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "====* FAILURES *====",
+            "*multiprocessing.pool.RemoteTraceback:*",
+            "Traceback (most recent call last):",
+            "*assert n == 10",
+            "The above exception was the direct cause of the following exception:",
+            "> * multitask_job()",
+        ]
+    )
 
 
-@pytest.mark.skipif("'__pypy__' in sys.builtin_module_names or sys.platform.startswith('java')")
+@pytest.mark.skipif(
+    "'__pypy__' in sys.builtin_module_names or sys.platform.startswith('java')"
+)
 def test_warn_missing(testdir):
     testdir.makepyfile("")
     result = testdir.run(sys.executable, "-OO", "-m", "pytest", "-h")
-    result.stderr.fnmatch_lines([
-        "*WARNING*assert statements are not executed*",
-    ])
+    result.stderr.fnmatch_lines(["*WARNING*assert statements are not executed*"])
     result = testdir.run(sys.executable, "-OO", "-m", "pytest")
-    result.stderr.fnmatch_lines([
-        "*WARNING*assert statements are not executed*",
-    ])
+    result.stderr.fnmatch_lines(["*WARNING*assert statements are not executed*"])
 
 
 def test_recursion_source_decode(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_something():
             pass
-    """)
-    testdir.makeini("""
+    """
+    )
+    testdir.makeini(
+        """
         [pytest]
         python_files = *.py
-    """)
+    """
+    )
     result = testdir.runpytest("--collect-only")
-    result.stdout.fnmatch_lines("""
+    result.stdout.fnmatch_lines(
+        """
         <Module*>
-    """)
+    """
+    )
 
 
 def test_AssertionError_message(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_hello():
             x,y = 1,2
             assert 0, (x,y)
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines("""
+    result.stdout.fnmatch_lines(
+        """
         *def test_hello*
         *assert 0, (x,y)*
         *AssertionError: (1, 2)*
-    """)
+    """
+    )
 
 
-@pytest.mark.skipif(PY3, reason='This bug does not exist on PY3')
+@pytest.mark.skipif(PY3, reason="This bug does not exist on PY3")
 def test_set_with_unsortable_elements():
     # issue #718
     class UnsortableKey(object):
+
         def __init__(self, name):
             self.name = name
 
         def __lt__(self, other):
             raise RuntimeError()
 
         def __repr__(self):
-            return 'repr({0})'.format(self.name)
+            return "repr({})".format(self.name)
 
         def __eq__(self, other):
             return self.name == other.name
 
         def __hash__(self):
             return hash(self.name)
 
-    left_set = set(UnsortableKey(str(i)) for i in range(1, 3))
-    right_set = set(UnsortableKey(str(i)) for i in range(2, 4))
+    left_set = {UnsortableKey(str(i)) for i in range(1, 3)}
+    right_set = {UnsortableKey(str(i)) for i in range(2, 4)}
     expl = callequal(left_set, right_set, verbose=True)
     # skip first line because it contains the "construction" of the set, which does not have a guaranteed order
     expl = expl[1:]
-    dedent = textwrap.dedent("""
+    dedent = textwrap.dedent(
+        """
         Extra items in the left set:
         repr(1)
         Extra items in the right set:
         repr(3)
         Full diff (fallback to calling repr on each item):
         - repr(1)
         repr(2)
         + repr(3)
-    """).strip()
-    assert '\n'.join(expl) == dedent
+    """
+    ).strip()
+    assert "\n".join(expl) == dedent
 
 
 def test_diff_newline_at_end(monkeypatch, testdir):
-    testdir.makepyfile(r"""
+    testdir.makepyfile(
+        r"""
         def test_diff():
             assert 'asdf' == 'asdf\n'
-    """)
+    """
+    )
 
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines(r"""
+    result.stdout.fnmatch_lines(
+        r"""
         *assert 'asdf' == 'asdf\n'
         *  - asdf
         *  + asdf
         *  ?     +
-    """)
+    """
+    )
 
 
 def test_assert_tuple_warning(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_tuple():
             assert(False, 'you shall not pass')
-    """)
-    result = testdir.runpytest('-rw')
-    result.stdout.fnmatch_lines([
-        '*test_assert_tuple_warning.py:2',
-        '*assertion is always true*',
-    ])
+    """
+    )
+    result = testdir.runpytest("-rw")
+    result.stdout.fnmatch_lines(
+        ["*test_assert_tuple_warning.py:2", "*assertion is always true*"]
+    )
 
 
 def test_assert_indirect_tuple_no_warning(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_tuple():
             tpl = ('foo', 'bar')
             assert tpl
-    """)
-    result = testdir.runpytest('-rw')
-    output = '\n'.join(result.stdout.lines)
-    assert 'WR1' not in output
+    """
+    )
+    result = testdir.runpytest("-rw")
+    output = "\n".join(result.stdout.lines)
+    assert "WR1" not in output
 
 
 def test_assert_with_unicode(monkeypatch, testdir):
-    testdir.makepyfile(u"""
+    testdir.makepyfile(
+        u"""
         # -*- coding: utf-8 -*-
         def test_unicode():
             assert u'유니코드' == u'Unicode'
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines(['*AssertionError*'])
+    result.stdout.fnmatch_lines(["*AssertionError*"])
 
 
 def test_raise_unprintable_assertion_error(testdir):
-    testdir.makepyfile(r"""
+    testdir.makepyfile(
+        r"""
         def test_raise_assertion_error():
             raise AssertionError('\xff')
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([r">       raise AssertionError('\xff')", 'E       AssertionError: *'])
+    result.stdout.fnmatch_lines(
+        [r">       raise AssertionError('\xff')", "E       AssertionError: *"]
+    )
 
 
 def test_raise_assertion_error_raisin_repr(testdir):
-    testdir.makepyfile(u"""
+    testdir.makepyfile(
+        u"""
         class RaisingRepr(object):
             def __repr__(self):
                 raise Exception()
         def test_raising_repr():
             raise AssertionError(RaisingRepr())
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines(['E       AssertionError: <unprintable AssertionError object>'])
+    result.stdout.fnmatch_lines(
+        ["E       AssertionError: <unprintable AssertionError object>"]
+    )
 
 
 def test_issue_1944(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def f():
             return
 
         assert f() == 10
-    """)
+    """
+    )
     result = testdir.runpytest()
     result.stdout.fnmatch_lines(["*1 error*"])
     assert "AttributeError: 'Module' object has no attribute '_obj'" not in result.stdout.str()
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_assertrewrite.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_assertrewrite.py
@@ -1,22 +1,27 @@
 from __future__ import absolute_import, division, print_function
 
 import glob
 import os
 import py_compile
 import stat
 import sys
+import textwrap
 import zipfile
 import py
 import pytest
 
 import _pytest._code
 from _pytest.assertion import util
-from _pytest.assertion.rewrite import rewrite_asserts, PYTEST_TAG, AssertionRewritingHook
+from _pytest.assertion.rewrite import (
+    rewrite_asserts,
+    PYTEST_TAG,
+    AssertionRewritingHook,
+)
 from _pytest.main import EXIT_NOTESTSCOLLECTED
 
 ast = pytest.importorskip("ast")
 if sys.platform.startswith("java"):
     # XXX should be xfail
     pytest.skip("assert rewrite does currently not work on jython")
 
 
@@ -33,17 +38,17 @@ def teardown_module(mod):
 def rewrite(src):
     tree = ast.parse(src)
     rewrite_asserts(tree)
     return tree
 
 
 def getmsg(f, extra_ns=None, must_pass=False):
     """Rewrite the assertions in f, run it, and get the failure message."""
-    src = '\n'.join(_pytest._code.Code(f).source().lines)
+    src = "\n".join(_pytest._code.Code(f).source().lines)
     mod = rewrite(src)
     code = compile(mod, "<test>", "exec")
     ns = {}
     if extra_ns is not None:
         ns.update(extra_ns)
     py.builtin.exec_(code, ns)
     func = ns[f.__name__]
     try:
@@ -55,58 +60,69 @@ def getmsg(f, extra_ns=None, must_pass=F
         if not s.startswith("assert"):
             return "AssertionError: " + s
         return s
     else:
         if not must_pass:
             pytest.fail("function didn't raise at all")
 
 
+def adjust_body_for_new_docstring_in_module_node(m):
+    """Module docstrings in 3.8 are part of Module node.
+    This was briefly in 3.7 as well but got reverted in beta 5.
+
+    It's not in the body so we remove it so the following body items have
+    the same indexes on all Python versions:
+
+    TODO:
+
+    We have a complicated sys.version_info if in here to ease testing on
+    various Python 3.7 versions, but we should remove the 3.7 check after
+    3.7 is released as stable to make this check more straightforward.
+    """
+    if (
+        sys.version_info < (3, 8)
+        and not ((3, 7) <= sys.version_info <= (3, 7, 0, "beta", 4))
+    ):
+        assert len(m.body) > 1
+        assert isinstance(m.body[0], ast.Expr)
+        assert isinstance(m.body[0].value, ast.Str)
+        del m.body[0]
+
+
 class TestAssertionRewrite(object):
 
     def test_place_initial_imports(self):
         s = """'Doc string'\nother = stuff"""
         m = rewrite(s)
-        # Module docstrings in 3.7 are part of Module node, it's not in the body
-        # so we remove it so the following body items have the same indexes on
-        # all Python versions
-        if sys.version_info < (3, 7):
-            assert isinstance(m.body[0], ast.Expr)
-            assert isinstance(m.body[0].value, ast.Str)
-            del m.body[0]
+        adjust_body_for_new_docstring_in_module_node(m)
         for imp in m.body[0:2]:
             assert isinstance(imp, ast.Import)
             assert imp.lineno == 2
             assert imp.col_offset == 0
         assert isinstance(m.body[2], ast.Assign)
         s = """from __future__ import with_statement\nother_stuff"""
         m = rewrite(s)
         assert isinstance(m.body[0], ast.ImportFrom)
         for imp in m.body[1:3]:
             assert isinstance(imp, ast.Import)
             assert imp.lineno == 2
             assert imp.col_offset == 0
         assert isinstance(m.body[3], ast.Expr)
         s = """'doc string'\nfrom __future__ import with_statement"""
         m = rewrite(s)
-        if sys.version_info < (3, 7):
-            assert isinstance(m.body[0], ast.Expr)
-            assert isinstance(m.body[0].value, ast.Str)
-            del m.body[0]
+        adjust_body_for_new_docstring_in_module_node(m)
         assert isinstance(m.body[0], ast.ImportFrom)
         for imp in m.body[1:3]:
             assert isinstance(imp, ast.Import)
             assert imp.lineno == 2
             assert imp.col_offset == 0
         s = """'doc string'\nfrom __future__ import with_statement\nother"""
         m = rewrite(s)
-        if sys.version_info < (3, 7):
-            assert isinstance(m.body[0], ast.Expr)
-            assert isinstance(m.body[0].value, ast.Str)
-            del m.body[0]
+        adjust_body_for_new_docstring_in_module_node(m)
         assert isinstance(m.body[0], ast.ImportFrom)
         for imp in m.body[1:3]:
             assert isinstance(imp, ast.Import)
             assert imp.lineno == 3
             assert imp.col_offset == 0
         assert isinstance(m.body[3], ast.Expr)
         s = """from . import relative\nother_stuff"""
         m = rewrite(s)
@@ -114,28 +130,35 @@ class TestAssertionRewrite(object):
             assert isinstance(imp, ast.Import)
             assert imp.lineno == 1
             assert imp.col_offset == 0
         assert isinstance(m.body[3], ast.Expr)
 
     def test_dont_rewrite(self):
         s = """'PYTEST_DONT_REWRITE'\nassert 14"""
         m = rewrite(s)
-        if sys.version_info < (3, 7):
-            assert len(m.body) == 2
-            assert isinstance(m.body[0], ast.Expr)
-            assert isinstance(m.body[0].value, ast.Str)
-            del m.body[0]
-        else:
-            assert len(m.body) == 1
+        adjust_body_for_new_docstring_in_module_node(m)
+        assert len(m.body) == 1
         assert m.body[0].msg is None
 
+    def test_dont_rewrite_plugin(self, testdir):
+        contents = {
+            "conftest.py": "pytest_plugins = 'plugin'; import plugin",
+            "plugin.py": "'PYTEST_DONT_REWRITE'",
+            "test_foo.py": "def test_foo(): pass",
+        }
+        testdir.makepyfile(**contents)
+        result = testdir.runpytest_subprocess()
+        assert "warnings" not in "".join(result.outlines)
+
     def test_name(self):
+
         def f():
             assert False
+
         assert getmsg(f) == "assert False"
 
         def f():
             f = False
             assert f
 
         assert getmsg(f) == "assert False"
 
@@ -153,82 +176,87 @@ class TestAssertionRewrite(object):
             assert cls == 42  # noqa
 
         class X(object):
             pass
 
         assert getmsg(f, {"cls": X}) == "assert cls == 42"
 
     def test_assert_already_has_message(self):
+
         def f():
             assert False, "something bad!"
+
         assert getmsg(f) == "AssertionError: something bad!\nassert False"
 
     def test_assertion_message(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_foo():
                 assert 1 == 2, "The failure message"
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == 1
-        result.stdout.fnmatch_lines([
-            "*AssertionError*The failure message*",
-            "*assert 1 == 2*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*AssertionError*The failure message*", "*assert 1 == 2*"]
+        )
 
     def test_assertion_message_multiline(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_foo():
                 assert 1 == 2, "A multiline\\nfailure message"
-        """)
-        result = testdir.runpytest()
-        assert result.ret == 1
-        result.stdout.fnmatch_lines([
-            "*AssertionError*A multiline*",
-            "*failure message*",
-            "*assert 1 == 2*",
-        ])
-
-    def test_assertion_message_tuple(self, testdir):
-        testdir.makepyfile("""
-            def test_foo():
-                assert 1 == 2, (1, 2)
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == 1
-        result.stdout.fnmatch_lines([
-            "*AssertionError*%s*" % repr((1, 2)),
-            "*assert 1 == 2*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*AssertionError*A multiline*", "*failure message*", "*assert 1 == 2*"]
+        )
 
-    def test_assertion_message_expr(self, testdir):
-        testdir.makepyfile("""
+    def test_assertion_message_tuple(self, testdir):
+        testdir.makepyfile(
+            """
             def test_foo():
-                assert 1 == 2, 1 + 2
-        """)
+                assert 1 == 2, (1, 2)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == 1
-        result.stdout.fnmatch_lines([
-            "*AssertionError*3*",
-            "*assert 1 == 2*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*AssertionError*%s*" % repr((1, 2)), "*assert 1 == 2*"]
+        )
+
+    def test_assertion_message_expr(self, testdir):
+        testdir.makepyfile(
+            """
+            def test_foo():
+                assert 1 == 2, 1 + 2
+        """
+        )
+        result = testdir.runpytest()
+        assert result.ret == 1
+        result.stdout.fnmatch_lines(["*AssertionError*3*", "*assert 1 == 2*"])
 
     def test_assertion_message_escape(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_foo():
                 assert 1 == 2, 'To be escaped: %'
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == 1
-        result.stdout.fnmatch_lines([
-            "*AssertionError: To be escaped: %",
-            "*assert 1 == 2",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*AssertionError: To be escaped: %", "*assert 1 == 2"]
+        )
 
     def test_boolop(self):
+
         def f():
             f = g = False
             assert f and g
 
         assert getmsg(f) == "assert (False)"
 
         def f():
             f = True
@@ -257,24 +285,30 @@ class TestAssertionRewrite(object):
         getmsg(f, must_pass=True)
 
         def x():
             return False
 
         def f():
             assert x() and x()
 
-        assert getmsg(f, {"x": x}) == """assert (False)
+        assert (
+            getmsg(f, {"x": x})
+            == """assert (False)
  +  where False = x()"""
+        )
 
         def f():
             assert False or x()
 
-        assert getmsg(f, {"x": x}) == """assert (False or False)
+        assert (
+            getmsg(f, {"x": x})
+            == """assert (False or False)
  +  where False = x()"""
+        )
 
         def f():
             assert 1 in {} and 2 in {}
 
         assert getmsg(f) == "assert (1 in {})"
 
         def f():
             x = 1
@@ -292,28 +326,30 @@ class TestAssertionRewrite(object):
 
         def f():
             f = g = h = lambda: True
             assert f() and g() and h()
 
         getmsg(f, must_pass=True)
 
     def test_short_circuit_evaluation(self):
+
         def f():
             assert True or explode  # noqa
 
         getmsg(f, must_pass=True)
 
         def f():
             x = 1
             assert x == 1 or x == 2
 
         getmsg(f, must_pass=True)
 
     def test_unary_op(self):
+
         def f():
             x = True
             assert not x
 
         assert getmsg(f) == "assert not True"
 
         def f():
             x = 0
@@ -329,118 +365,153 @@ class TestAssertionRewrite(object):
 
         def f():
             x = 0
             assert +x + x
 
         assert getmsg(f) == "assert (+0 + 0)"
 
     def test_binary_op(self):
+
         def f():
             x = 1
             y = -1
             assert x + y
 
         assert getmsg(f) == "assert (1 + -1)"
 
         def f():
             assert not 5 % 4
+
         assert getmsg(f) == "assert not (5 % 4)"
 
     def test_boolop_percent(self):
+
         def f():
             assert 3 % 2 and False
 
         assert getmsg(f) == "assert ((3 % 2) and False)"
 
         def f():
             assert False or 4 % 2
+
         assert getmsg(f) == "assert (False or (4 % 2))"
 
     @pytest.mark.skipif("sys.version_info < (3,5)")
     def test_at_operator_issue1290(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             class Matrix(object):
                 def __init__(self, num):
                     self.num = num
                 def __matmul__(self, other):
                     return self.num * other.num
 
             def test_multmat_operator():
-                assert Matrix(2) @ Matrix(3) == 6""")
+                assert Matrix(2) @ Matrix(3) == 6"""
+        )
         testdir.runpytest().assert_outcomes(passed=1)
 
     def test_call(self):
+
         def g(a=42, *args, **kwargs):
             return False
 
         ns = {"g": g}
 
         def f():
             assert g()
 
-        assert getmsg(f, ns) == """assert False
+        assert (
+            getmsg(f, ns)
+            == """assert False
  +  where False = g()"""
+        )
 
         def f():
             assert g(1)
 
-        assert getmsg(f, ns) == """assert False
+        assert (
+            getmsg(f, ns)
+            == """assert False
  +  where False = g(1)"""
+        )
 
         def f():
             assert g(1, 2)
 
-        assert getmsg(f, ns) == """assert False
+        assert (
+            getmsg(f, ns)
+            == """assert False
  +  where False = g(1, 2)"""
+        )
 
         def f():
             assert g(1, g=42)
 
-        assert getmsg(f, ns) == """assert False
+        assert (
+            getmsg(f, ns)
+            == """assert False
  +  where False = g(1, g=42)"""
+        )
 
         def f():
             assert g(1, 3, g=23)
 
-        assert getmsg(f, ns) == """assert False
+        assert (
+            getmsg(f, ns)
+            == """assert False
  +  where False = g(1, 3, g=23)"""
+        )
 
         def f():
             seq = [1, 2, 3]
             assert g(*seq)
 
-        assert getmsg(f, ns) == """assert False
+        assert (
+            getmsg(f, ns)
+            == """assert False
  +  where False = g(*[1, 2, 3])"""
+        )
 
         def f():
             x = "a"
             assert g(**{x: 2})
 
-        assert getmsg(f, ns) == """assert False
+        assert (
+            getmsg(f, ns)
+            == """assert False
  +  where False = g(**{'a': 2})"""
+        )
 
     def test_attribute(self):
+
         class X(object):
             g = 3
 
         ns = {"x": X}
 
         def f():
             assert not x.g  # noqa
 
-        assert getmsg(f, ns) == """assert not 3
+        assert (
+            getmsg(f, ns)
+            == """assert not 3
  +  where 3 = x.g"""
+        )
 
         def f():
             x.a = False  # noqa
-            assert x.a   # noqa
+            assert x.a  # noqa
 
-        assert getmsg(f, ns) == """assert False
+        assert (
+            getmsg(f, ns)
+            == """assert False
  +  where False = x.a"""
+        )
 
     def test_comparisons(self):
 
         def f():
             a, b = range(2)
             assert b < a
 
         assert getmsg(f) == """assert 1 < 0"""
@@ -471,20 +542,23 @@ class TestAssertionRewrite(object):
         getmsg(f, must_pass=True)
 
     def test_len(self):
 
         def f():
             values = list(range(10))
             assert len(values) == 11
 
-        assert getmsg(f).startswith("""assert 10 == 11
- +  where 10 = len([""")
+        assert getmsg(f).startswith(
+            """assert 10 == 11
+ +  where 10 = len(["""
+        )
 
     def test_custom_reprcompare(self, monkeypatch):
+
         def my_reprcompare(op, left, right):
             return "42"
 
         monkeypatch.setattr(util, "_reprcompare", my_reprcompare)
 
         def f():
             assert 42 < 3
 
@@ -496,17 +570,19 @@ class TestAssertionRewrite(object):
         monkeypatch.setattr(util, "_reprcompare", my_reprcompare)
 
         def f():
             assert 1 < 3 < 5 <= 4 < 7
 
         assert getmsg(f) == "assert 5 <= 4"
 
     def test_assert_raising_nonzero_in_comparison(self):
+
         def f():
+
             class A(object):
 
                 def __nonzero__(self):
                     raise ValueError(42)
 
                 def __lt__(self, other):
                     return A()
 
@@ -516,481 +592,553 @@ class TestAssertionRewrite(object):
             def myany(x):
                 return False
 
             assert myany(A() < 0)
 
         assert "<MY42 object> < 0" in getmsg(f)
 
     def test_formatchar(self):
+
         def f():
             assert "%test" == "test"
 
         assert getmsg(f).startswith("assert '%test' == 'test'")
 
     def test_custom_repr(self):
+
         def f():
+
             class Foo(object):
                 a = 1
 
                 def __repr__(self):
                     return "\n{ \n~ \n}"
 
             f = Foo()
             assert 0 == f.a
 
         assert r"where 1 = \n{ \n~ \n}.a" in util._format_lines([getmsg(f)])[0]
 
 
 class TestRewriteOnImport(object):
 
     def test_pycache_is_a_file(self, testdir):
         testdir.tmpdir.join("__pycache__").write("Hello")
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_rewritten():
-                assert "@py_builtins" in globals()""")
+                assert "@py_builtins" in globals()"""
+        )
         assert testdir.runpytest().ret == 0
 
     def test_pycache_is_readonly(self, testdir):
         cache = testdir.tmpdir.mkdir("__pycache__")
         old_mode = cache.stat().mode
         cache.chmod(old_mode ^ stat.S_IWRITE)
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_rewritten():
-                assert "@py_builtins" in globals()""")
+                assert "@py_builtins" in globals()"""
+        )
         try:
             assert testdir.runpytest().ret == 0
         finally:
             cache.chmod(old_mode)
 
     def test_zipfile(self, testdir):
         z = testdir.tmpdir.join("myzip.zip")
         z_fn = str(z)
         f = zipfile.ZipFile(z_fn, "w")
         try:
             f.writestr("test_gum/__init__.py", "")
             f.writestr("test_gum/test_lizard.py", "")
         finally:
             f.close()
         z.chmod(256)
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import sys
             sys.path.append(%r)
-            import test_gum.test_lizard""" % (z_fn,))
+            import test_gum.test_lizard"""
+            % (z_fn,)
+        )
         assert testdir.runpytest().ret == EXIT_NOTESTSCOLLECTED
 
     def test_readonly(self, testdir):
         sub = testdir.mkdir("testing")
         sub.join("test_readonly.py").write(
-            py.builtin._totext("""
+            py.builtin._totext(
+                """
 def test_rewritten():
     assert "@py_builtins" in globals()
-            """).encode("utf-8"), "wb")
+            """
+            ).encode(
+                "utf-8"
+            ),
+            "wb",
+        )
         old_mode = sub.stat().mode
         sub.chmod(320)
         try:
             assert testdir.runpytest().ret == 0
         finally:
             sub.chmod(old_mode)
 
     def test_dont_write_bytecode(self, testdir, monkeypatch):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import os
             def test_no_bytecode():
                 assert "__pycache__" in __cached__
                 assert not os.path.exists(__cached__)
-                assert not os.path.exists(os.path.dirname(__cached__))""")
+                assert not os.path.exists(os.path.dirname(__cached__))"""
+        )
         monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", "1")
         assert testdir.runpytest_subprocess().ret == 0
 
     def test_orphaned_pyc_file(self, testdir):
-        if sys.version_info < (3, 0) and hasattr(sys, 'pypy_version_info'):
+        if sys.version_info < (3, 0) and hasattr(sys, "pypy_version_info"):
             pytest.skip("pypy2 doesn't run orphaned pyc files")
 
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import orphan
             def test_it():
                 assert orphan.value == 17
-            """)
-        testdir.makepyfile(orphan="""
+            """
+        )
+        testdir.makepyfile(
+            orphan="""
             value = 17
-            """)
+            """
+        )
         py_compile.compile("orphan.py")
         os.remove("orphan.py")
 
         # Python 3 puts the .pyc files in a __pycache__ directory, and will
         # not import from there without source.  It will import a .pyc from
         # the source location though.
         if not os.path.exists("orphan.pyc"):
             pycs = glob.glob("__pycache__/orphan.*.pyc")
             assert len(pycs) == 1
             os.rename(pycs[0], "orphan.pyc")
 
         assert testdir.runpytest().ret == 0
 
     @pytest.mark.skipif('"__pypy__" in sys.modules')
     def test_pyc_vs_pyo(self, testdir, monkeypatch):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def test_optimized():
                 "hello"
                 assert test_optimized.__doc__ is None"""
-                           )
-        p = py.path.local.make_numbered_dir(prefix="runpytest-", keep=None,
-                                            rootdir=testdir.tmpdir)
+        )
+        p = py.path.local.make_numbered_dir(
+            prefix="runpytest-", keep=None, rootdir=testdir.tmpdir
+        )
         tmp = "--basetemp=%s" % p
         monkeypatch.setenv("PYTHONOPTIMIZE", "2")
         monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
         assert testdir.runpytest_subprocess(tmp).ret == 0
         tagged = "test_pyc_vs_pyo." + PYTEST_TAG
         assert tagged + ".pyo" in os.listdir("__pycache__")
         monkeypatch.undo()
         monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
         assert testdir.runpytest_subprocess(tmp).ret == 1
         assert tagged + ".pyc" in os.listdir("__pycache__")
 
     def test_package(self, testdir):
         pkg = testdir.tmpdir.join("pkg")
         pkg.mkdir()
         pkg.join("__init__.py").ensure()
-        pkg.join("test_blah.py").write("""
+        pkg.join("test_blah.py").write(
+            """
 def test_rewritten():
-    assert "@py_builtins" in globals()""")
+    assert "@py_builtins" in globals()"""
+        )
         assert testdir.runpytest().ret == 0
 
     def test_translate_newlines(self, testdir):
         content = "def test_rewritten():\r\n assert '@py_builtins' in globals()"
         b = content.encode("utf-8")
         testdir.tmpdir.join("test_newlines.py").write(b, "wb")
         assert testdir.runpytest().ret == 0
 
-    @pytest.mark.skipif(sys.version_info < (3, 4),
-                        reason='packages without __init__.py not supported on python 2')
+    @pytest.mark.skipif(
+        sys.version_info < (3, 4),
+        reason="packages without __init__.py not supported on python 2",
+    )
     def test_package_without__init__py(self, testdir):
-        pkg = testdir.mkdir('a_package_without_init_py')
-        pkg.join('module.py').ensure()
+        pkg = testdir.mkdir("a_package_without_init_py")
+        pkg.join("module.py").ensure()
         testdir.makepyfile("import a_package_without_init_py.module")
         assert testdir.runpytest().ret == EXIT_NOTESTSCOLLECTED
 
     def test_rewrite_warning(self, pytestconfig, monkeypatch):
         hook = AssertionRewritingHook(pytestconfig)
         warnings = []
 
         def mywarn(code, msg):
             warnings.append((code, msg))
 
-        monkeypatch.setattr(hook.config, 'warn', mywarn)
-        hook.mark_rewrite('_pytest')
-        assert '_pytest' in warnings[0][1]
+        monkeypatch.setattr(hook.config, "warn", mywarn)
+        hook.mark_rewrite("_pytest")
+        assert "_pytest" in warnings[0][1]
 
     def test_rewrite_module_imported_from_conftest(self, testdir):
-        testdir.makeconftest('''
+        testdir.makeconftest(
+            """
             import test_rewrite_module_imported
-        ''')
-        testdir.makepyfile(test_rewrite_module_imported='''
+        """
+        )
+        testdir.makepyfile(
+            test_rewrite_module_imported="""
             def test_rewritten():
                 assert "@py_builtins" in globals()
-        ''')
+        """
+        )
         assert testdir.runpytest_subprocess().ret == 0
 
     def test_remember_rewritten_modules(self, pytestconfig, testdir, monkeypatch):
         """
         AssertionRewriteHook should remember rewritten modules so it
         doesn't give false positives (#2005).
         """
         monkeypatch.syspath_prepend(testdir.tmpdir)
-        testdir.makepyfile(test_remember_rewritten_modules='')
+        testdir.makepyfile(test_remember_rewritten_modules="")
         warnings = []
         hook = AssertionRewritingHook(pytestconfig)
-        monkeypatch.setattr(hook.config, 'warn', lambda code, msg: warnings.append(msg))
-        hook.find_module('test_remember_rewritten_modules')
-        hook.load_module('test_remember_rewritten_modules')
-        hook.mark_rewrite('test_remember_rewritten_modules')
-        hook.mark_rewrite('test_remember_rewritten_modules')
+        monkeypatch.setattr(hook.config, "warn", lambda code, msg: warnings.append(msg))
+        hook.find_module("test_remember_rewritten_modules")
+        hook.load_module("test_remember_rewritten_modules")
+        hook.mark_rewrite("test_remember_rewritten_modules")
+        hook.mark_rewrite("test_remember_rewritten_modules")
         assert warnings == []
 
     def test_rewrite_warning_using_pytest_plugins(self, testdir):
-        testdir.makepyfile(**{
-            'conftest.py': "pytest_plugins = ['core', 'gui', 'sci']",
-            'core.py': "",
-            'gui.py': "pytest_plugins = ['core', 'sci']",
-            'sci.py': "pytest_plugins = ['core']",
-            'test_rewrite_warning_pytest_plugins.py': "def test(): pass",
-        })
+        testdir.makepyfile(
+            **{
+                "conftest.py": "pytest_plugins = ['core', 'gui', 'sci']",
+                "core.py": "",
+                "gui.py": "pytest_plugins = ['core', 'sci']",
+                "sci.py": "pytest_plugins = ['core']",
+                "test_rewrite_warning_pytest_plugins.py": "def test(): pass",
+            }
+        )
         testdir.chdir()
         result = testdir.runpytest_subprocess()
-        result.stdout.fnmatch_lines(['*= 1 passed in *=*'])
-        assert 'pytest-warning summary' not in result.stdout.str()
+        result.stdout.fnmatch_lines(["*= 1 passed in *=*"])
+        assert "pytest-warning summary" not in result.stdout.str()
 
     def test_rewrite_warning_using_pytest_plugins_env_var(self, testdir, monkeypatch):
-        monkeypatch.setenv('PYTEST_PLUGINS', 'plugin')
-        testdir.makepyfile(**{
-            'plugin.py': "",
-            'test_rewrite_warning_using_pytest_plugins_env_var.py': """
+        monkeypatch.setenv("PYTEST_PLUGINS", "plugin")
+        testdir.makepyfile(
+            **{
+                "plugin.py": "",
+                "test_rewrite_warning_using_pytest_plugins_env_var.py": """
                 import plugin
                 pytest_plugins = ['plugin']
                 def test():
                     pass
             """,
-        })
+            }
+        )
         testdir.chdir()
         result = testdir.runpytest_subprocess()
-        result.stdout.fnmatch_lines(['*= 1 passed in *=*'])
-        assert 'pytest-warning summary' not in result.stdout.str()
+        result.stdout.fnmatch_lines(["*= 1 passed in *=*"])
+        assert "pytest-warning summary" not in result.stdout.str()
 
-    @pytest.mark.skipif(sys.version_info[0] > 2, reason='python 2 only')
+    @pytest.mark.skipif(sys.version_info[0] > 2, reason="python 2 only")
     def test_rewrite_future_imports(self, testdir):
         """Test that rewritten modules don't inherit the __future__ flags
         from the assertrewrite module.
 
         assertion.rewrite imports __future__.division (and others), so
         ensure rewritten modules don't inherit those flags.
 
         The test below will fail if __future__.division is enabled
         """
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            """
             def test():
                 x = 1 / 2
                 assert type(x) is int
-        ''')
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == 0
 
 
 class TestAssertionRewriteHookDetails(object):
+
     def test_loader_is_package_false_for_module(self, testdir):
-        testdir.makepyfile(test_fun="""
+        testdir.makepyfile(
+            test_fun="""
             def test_loader():
                 assert not __loader__.is_package(__name__)
-            """)
+            """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "* 1 passed*",
-        ])
+        result.stdout.fnmatch_lines(["* 1 passed*"])
 
     def test_loader_is_package_true_for_package(self, testdir):
-        testdir.makepyfile(test_fun="""
+        testdir.makepyfile(
+            test_fun="""
             def test_loader():
                 assert not __loader__.is_package(__name__)
 
             def test_fun():
                 assert __loader__.is_package('fun')
 
             def test_missing():
                 assert not __loader__.is_package('pytest_not_there')
-            """)
-        testdir.mkpydir('fun')
+            """
+        )
+        testdir.mkpydir("fun")
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            '* 3 passed*',
-        ])
+        result.stdout.fnmatch_lines(["* 3 passed*"])
 
     @pytest.mark.skipif("sys.version_info[0] >= 3")
     @pytest.mark.xfail("hasattr(sys, 'pypy_translation_info')")
     def test_assume_ascii(self, testdir):
         content = "u'\xe2\x99\xa5\x01\xfe'"
         testdir.tmpdir.join("test_encoding.py").write(content, "wb")
         res = testdir.runpytest()
         assert res.ret != 0
         assert "SyntaxError: Non-ASCII character" in res.stdout.str()
 
     @pytest.mark.skipif("sys.version_info[0] >= 3")
     def test_detect_coding_cookie(self, testdir):
-        testdir.makepyfile(test_cookie="""
+        testdir.makepyfile(
+            test_cookie="""
             # -*- coding: utf-8 -*-
             u"St\xc3\xa4d"
             def test_rewritten():
-                assert "@py_builtins" in globals()""")
+                assert "@py_builtins" in globals()"""
+        )
         assert testdir.runpytest().ret == 0
 
     @pytest.mark.skipif("sys.version_info[0] >= 3")
     def test_detect_coding_cookie_second_line(self, testdir):
-        testdir.makepyfile(test_cookie="""
+        testdir.makepyfile(
+            test_cookie="""
             # -*- coding: utf-8 -*-
             u"St\xc3\xa4d"
             def test_rewritten():
-                assert "@py_builtins" in globals()""")
+                assert "@py_builtins" in globals()"""
+        )
         assert testdir.runpytest().ret == 0
 
     @pytest.mark.skipif("sys.version_info[0] >= 3")
     def test_detect_coding_cookie_crlf(self, testdir):
-        testdir.makepyfile(test_cookie="""
+        testdir.makepyfile(
+            test_cookie="""
             # -*- coding: utf-8 -*-
             u"St\xc3\xa4d"
             def test_rewritten():
-                assert "@py_builtins" in globals()""")
+                assert "@py_builtins" in globals()"""
+        )
         assert testdir.runpytest().ret == 0
 
     def test_sys_meta_path_munged(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_meta_path():
-                import sys; sys.meta_path = []""")
+                import sys; sys.meta_path = []"""
+        )
         assert testdir.runpytest().ret == 0
 
     def test_write_pyc(self, testdir, tmpdir, monkeypatch):
         from _pytest.assertion.rewrite import _write_pyc
         from _pytest.assertion import AssertionState
-        try:
-            import __builtin__ as b
-        except ImportError:
-            import builtins as b
+        import atomicwrites
+        from contextlib import contextmanager
+
         config = testdir.parseconfig([])
         state = AssertionState(config, "rewrite")
         source_path = tmpdir.ensure("source.py")
         pycpath = tmpdir.join("pyc").strpath
         assert _write_pyc(state, [1], source_path.stat(), pycpath)
 
-        def open(*args):
+        @contextmanager
+        def atomic_write_failed(fn, mode="r", overwrite=False):
             e = IOError()
             e.errno = 10
             raise e
+            yield  # noqa
 
-        monkeypatch.setattr(b, "open", open)
+        monkeypatch.setattr(atomicwrites, "atomic_write", atomic_write_failed)
         assert not _write_pyc(state, [1], source_path.stat(), pycpath)
 
     def test_resources_provider_for_loader(self, testdir):
         """
         Attempts to load resources from a package should succeed normally,
         even when the AssertionRewriteHook is used to load the modules.
 
         See #366 for details.
         """
         pytest.importorskip("pkg_resources")
 
-        testdir.mkpydir('testpkg')
+        testdir.mkpydir("testpkg")
         contents = {
-            'testpkg/test_pkg': """
+            "testpkg/test_pkg": """
                 import pkg_resources
 
                 import pytest
                 from _pytest.assertion.rewrite import AssertionRewritingHook
 
                 def test_load_resource():
                     assert isinstance(__loader__, AssertionRewritingHook)
                     res = pkg_resources.resource_string(__name__, 'resource.txt')
                     res = res.decode('ascii')
                     assert res == 'Load me please.'
-                """,
+                """
         }
         testdir.makepyfile(**contents)
-        testdir.maketxtfile(**{'testpkg/resource': "Load me please."})
+        testdir.maketxtfile(**{"testpkg/resource": "Load me please."})
 
         result = testdir.runpytest_subprocess()
         result.assert_outcomes(passed=1)
 
     def test_read_pyc(self, tmpdir):
         """
         Ensure that the `_read_pyc` can properly deal with corrupted pyc files.
         In those circumstances it should just give up instead of generating
         an exception that is propagated to the caller.
         """
         import py_compile
         from _pytest.assertion.rewrite import _read_pyc
 
-        source = tmpdir.join('source.py')
-        pyc = source + 'c'
+        source = tmpdir.join("source.py")
+        pyc = source + "c"
 
-        source.write('def test(): pass')
+        source.write("def test(): pass")
         py_compile.compile(str(source), str(pyc))
 
-        contents = pyc.read(mode='rb')
+        contents = pyc.read(mode="rb")
         strip_bytes = 20  # header is around 8 bytes, strip a little more
         assert len(contents) > strip_bytes
-        pyc.write(contents[:strip_bytes], mode='wb')
+        pyc.write(contents[:strip_bytes], mode="wb")
 
         assert _read_pyc(source, str(pyc)) is None  # no error
 
     def test_reload_is_same(self, testdir):
         # A file that will be picked up during collecting.
         testdir.tmpdir.join("file.py").ensure()
-        testdir.tmpdir.join("pytest.ini").write(py.std.textwrap.dedent("""
+        testdir.tmpdir.join("pytest.ini").write(
+            textwrap.dedent(
+                """
             [pytest]
             python_files = *.py
-        """))
+        """
+            )
+        )
 
-        testdir.makepyfile(test_fun="""
+        testdir.makepyfile(
+            test_fun="""
             import sys
             try:
                 from imp import reload
             except ImportError:
                 pass
 
             def test_loader():
                 import file
                 assert sys.modules["file"] is reload(file)
-            """)
-        result = testdir.runpytest('-s')
-        result.stdout.fnmatch_lines([
-            "* 1 passed*",
-        ])
+            """
+        )
+        result = testdir.runpytest("-s")
+        result.stdout.fnmatch_lines(["* 1 passed*"])
 
     def test_get_data_support(self, testdir):
         """Implement optional PEP302 api (#808).
         """
         path = testdir.mkpydir("foo")
-        path.join("test_foo.py").write(_pytest._code.Source("""
+        path.join("test_foo.py").write(
+            _pytest._code.Source(
+                """
             class Test(object):
                 def test_foo(self):
                     import pkgutil
                     data = pkgutil.get_data('foo.test_foo', 'data.txt')
                     assert data == b'Hey'
-        """))
-        path.join('data.txt').write('Hey')
+        """
+            )
+        )
+        path.join("data.txt").write("Hey")
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines('*1 passed*')
+        result.stdout.fnmatch_lines("*1 passed*")
 
 
 def test_issue731(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
     class LongReprWithBraces(object):
         def __repr__(self):
            return 'LongReprWithBraces({' + ('a' * 80) + '}' + ('a' * 120) + ')'
 
         def some_method(self):
             return False
 
     def test_long_repr():
         obj = LongReprWithBraces()
         assert obj.some_method()
-    """)
+    """
+    )
     result = testdir.runpytest()
-    assert 'unbalanced braces' not in result.stdout.str()
+    assert "unbalanced braces" not in result.stdout.str()
 
 
 class TestIssue925(object):
+
     def test_simple_case(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
         def test_ternary_display():
             assert (False == False) == False
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines('*E*assert (False == False) == False')
+        result.stdout.fnmatch_lines("*E*assert (False == False) == False")
 
     def test_long_case(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
         def test_ternary_display():
              assert False == (False == True) == True
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines('*E*assert (False == True) == True')
+        result.stdout.fnmatch_lines("*E*assert (False == True) == True")
 
     def test_many_brackets(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_ternary_display():
                  assert True == ((False == True) == True)
-            """)
+            """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines('*E*assert True == ((False == True) == True)')
+        result.stdout.fnmatch_lines("*E*assert True == ((False == True) == True)")
 
 
 class TestIssue2121():
+
     def test_simple(self, testdir):
-        testdir.tmpdir.join("tests/file.py").ensure().write("""
+        testdir.tmpdir.join("tests/file.py").ensure().write(
+            """
 def test_simple_failure():
     assert 1 + 1 == 3
-""")
-        testdir.tmpdir.join("pytest.ini").write(py.std.textwrap.dedent("""
+"""
+        )
+        testdir.tmpdir.join("pytest.ini").write(
+            textwrap.dedent(
+                """
             [pytest]
             python_files = tests/**.py
-        """))
+        """
+            )
+        )
 
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines('*E*assert (1 + 1) == 3')
+        result.stdout.fnmatch_lines("*E*assert (1 + 1) == 3")
old mode 100755
new mode 100644
rename from testing/web-platform/tests/tools/third_party/pytest/testing/test_cache.py
rename to testing/web-platform/tests/tools/third_party/pytest/testing/test_cacheprovider.py
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_cache.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_cacheprovider.py
@@ -5,16 +5,17 @@ import _pytest
 import pytest
 import os
 import shutil
 
 pytest_plugins = "pytester",
 
 
 class TestNewAPI(object):
+
     def test_config_cache_makedir(self, testdir):
         testdir.makeini("[pytest]")
         config = testdir.parseconfigure()
         with pytest.raises(ValueError):
             config.cache.makedir("key/name")
 
         p = config.cache.makedir("name")
         assert p.check()
@@ -26,580 +27,794 @@ class TestNewAPI(object):
         pytest.raises(TypeError, lambda: cache.set("key/name", cache))
         config.cache.set("key/name", 0)
         config.cache._getvaluepath("key/name").write("123invalid")
         val = config.cache.get("key/name", -2)
         assert val == -2
 
     def test_cache_writefail_cachfile_silent(self, testdir):
         testdir.makeini("[pytest]")
-        testdir.tmpdir.join('.cache').write('gone wrong')
+        testdir.tmpdir.join(".pytest_cache").write("gone wrong")
         config = testdir.parseconfigure()
         cache = config.cache
-        cache.set('test/broken', [])
+        cache.set("test/broken", [])
 
-    @pytest.mark.skipif(sys.platform.startswith('win'), reason='no chmod on windows')
+    @pytest.mark.skipif(sys.platform.startswith("win"), reason="no chmod on windows")
     def test_cache_writefail_permissions(self, testdir):
         testdir.makeini("[pytest]")
-        testdir.tmpdir.ensure_dir('.cache').chmod(0)
+        testdir.tmpdir.ensure_dir(".pytest_cache").chmod(0)
         config = testdir.parseconfigure()
         cache = config.cache
-        cache.set('test/broken', [])
+        cache.set("test/broken", [])
 
-    @pytest.mark.skipif(sys.platform.startswith('win'), reason='no chmod on windows')
+    @pytest.mark.skipif(sys.platform.startswith("win"), reason="no chmod on windows")
     def test_cache_failure_warns(self, testdir):
-        testdir.tmpdir.ensure_dir('.cache').chmod(0)
-        testdir.makepyfile("""
+        testdir.tmpdir.ensure_dir(".pytest_cache").chmod(0)
+        testdir.makepyfile(
+            """
             def test_error():
                 raise Exception
 
-        """)
-        result = testdir.runpytest('-rw')
+        """
+        )
+        result = testdir.runpytest("-rw")
         assert result.ret == 1
-        result.stdout.fnmatch_lines([
-            "*could not create cache path*",
-            "*1 warnings*",
-        ])
+        result.stdout.fnmatch_lines(["*could not create cache path*", "*2 warnings*"])
 
     def test_config_cache(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_configure(config):
                 # see that we get cache information early on
                 assert hasattr(config, "cache")
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             def test_session(pytestconfig):
                 assert hasattr(pytestconfig, "cache")
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == 0
         result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_cachefuncarg(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def test_cachefuncarg(cache):
                 val = cache.get("some/thing", None)
                 assert val is None
                 cache.set("some/thing", [1])
                 pytest.raises(TypeError, lambda: cache.get("some/thing"))
                 val = cache.get("some/thing", [])
                 assert val == [1]
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.ret == 0
         result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_custom_rel_cache_dir(self, testdir):
-        rel_cache_dir = os.path.join('custom_cache_dir', 'subdir')
-        testdir.makeini("""
+        rel_cache_dir = os.path.join("custom_cache_dir", "subdir")
+        testdir.makeini(
+            """
             [pytest]
             cache_dir = {cache_dir}
-        """.format(cache_dir=rel_cache_dir))
-        testdir.makepyfile(test_errored='def test_error():\n    assert False')
+        """.format(
+                cache_dir=rel_cache_dir
+            )
+        )
+        testdir.makepyfile(test_errored="def test_error():\n    assert False")
         testdir.runpytest()
         assert testdir.tmpdir.join(rel_cache_dir).isdir()
 
     def test_custom_abs_cache_dir(self, testdir, tmpdir_factory):
-        tmp = str(tmpdir_factory.mktemp('tmp'))
-        abs_cache_dir = os.path.join(tmp, 'custom_cache_dir')
-        testdir.makeini("""
+        tmp = str(tmpdir_factory.mktemp("tmp"))
+        abs_cache_dir = os.path.join(tmp, "custom_cache_dir")
+        testdir.makeini(
+            """
             [pytest]
             cache_dir = {cache_dir}
-        """.format(cache_dir=abs_cache_dir))
-        testdir.makepyfile(test_errored='def test_error():\n    assert False')
+        """.format(
+                cache_dir=abs_cache_dir
+            )
+        )
+        testdir.makepyfile(test_errored="def test_error():\n    assert False")
         testdir.runpytest()
         assert py.path.local(abs_cache_dir).isdir()
 
     def test_custom_cache_dir_with_env_var(self, testdir, monkeypatch):
-        monkeypatch.setenv('env_var', 'custom_cache_dir')
-        testdir.makeini("""
+        monkeypatch.setenv("env_var", "custom_cache_dir")
+        testdir.makeini(
+            """
             [pytest]
             cache_dir = {cache_dir}
-        """.format(cache_dir='$env_var'))
-        testdir.makepyfile(test_errored='def test_error():\n    assert False')
+        """.format(
+                cache_dir="$env_var"
+            )
+        )
+        testdir.makepyfile(test_errored="def test_error():\n    assert False")
         testdir.runpytest()
-        assert testdir.tmpdir.join('custom_cache_dir').isdir()
+        assert testdir.tmpdir.join("custom_cache_dir").isdir()
 
 
 def test_cache_reportheader(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_hello():
             pass
-    """)
+    """
+    )
     result = testdir.runpytest("-v")
-    result.stdout.fnmatch_lines([
-        "cachedir: .cache"
-    ])
+    result.stdout.fnmatch_lines(["cachedir: .pytest_cache"])
 
 
 def test_cache_show(testdir):
     result = testdir.runpytest("--cache-show")
     assert result.ret == 0
-    result.stdout.fnmatch_lines([
-        "*cache is empty*"
-    ])
-    testdir.makeconftest("""
+    result.stdout.fnmatch_lines(["*cache is empty*"])
+    testdir.makeconftest(
+        """
         def pytest_configure(config):
             config.cache.set("my/name", [1,2,3])
             config.cache.set("other/some", {1:2})
             dp = config.cache.makedir("mydb")
             dp.ensure("hello")
             dp.ensure("world")
-    """)
+    """
+    )
     result = testdir.runpytest()
     assert result.ret == 5  # no tests executed
     result = testdir.runpytest("--cache-show")
-    result.stdout.fnmatch_lines_random([
-        "*cachedir:*",
-        "-*cache values*-",
-        "*my/name contains:",
-        "  [1, 2, 3]",
-        "*other/some contains*",
-        "  {*1*: 2}",
-        "-*cache directories*-",
-        "*mydb/hello*length 0*",
-        "*mydb/world*length 0*",
-    ])
+    result.stdout.fnmatch_lines_random(
+        [
+            "*cachedir:*",
+            "-*cache values*-",
+            "*my/name contains:",
+            "  [1, 2, 3]",
+            "*other/some contains*",
+            "  {*1*: 2}",
+            "-*cache directories*-",
+            "*mydb/hello*length 0*",
+            "*mydb/world*length 0*",
+        ]
+    )
 
 
 class TestLastFailed(object):
 
     def test_lastfailed_usecase(self, testdir, monkeypatch):
         monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", 1)
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_1():
                 assert 0
             def test_2():
                 assert 0
             def test_3():
                 assert 1
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*2 failed*",
-        ])
-        p.write(_pytest._code.Source("""
+        result.stdout.fnmatch_lines(["*2 failed*"])
+        p.write(
+            _pytest._code.Source(
+                """
             def test_1():
                 assert 1
 
             def test_2():
                 assert 1
 
             def test_3():
                 assert 0
-        """))
-        result = testdir.runpytest("--lf")
-        result.stdout.fnmatch_lines([
-            "*2 passed*1 desel*",
-        ])
+        """
+            )
+        )
         result = testdir.runpytest("--lf")
-        result.stdout.fnmatch_lines([
-            "*1 failed*2 passed*",
-        ])
+        result.stdout.fnmatch_lines(["*2 passed*1 desel*"])
+        result = testdir.runpytest("--lf")
+        result.stdout.fnmatch_lines(["*1 failed*2 passed*"])
         result = testdir.runpytest("--lf", "--cache-clear")
-        result.stdout.fnmatch_lines([
-            "*1 failed*2 passed*",
-        ])
+        result.stdout.fnmatch_lines(["*1 failed*2 passed*"])
 
         # Run this again to make sure clear-cache is robust
-        if os.path.isdir('.cache'):
-            shutil.rmtree('.cache')
+        if os.path.isdir(".pytest_cache"):
+            shutil.rmtree(".pytest_cache")
         result = testdir.runpytest("--lf", "--cache-clear")
-        result.stdout.fnmatch_lines([
-            "*1 failed*2 passed*",
-        ])
+        result.stdout.fnmatch_lines(["*1 failed*2 passed*"])
 
     def test_failedfirst_order(self, testdir):
-        testdir.tmpdir.join('test_a.py').write(_pytest._code.Source("""
+        testdir.tmpdir.join("test_a.py").write(
+            _pytest._code.Source(
+                """
             def test_always_passes():
                 assert 1
-        """))
-        testdir.tmpdir.join('test_b.py').write(_pytest._code.Source("""
+        """
+            )
+        )
+        testdir.tmpdir.join("test_b.py").write(
+            _pytest._code.Source(
+                """
             def test_always_fails():
                 assert 0
-        """))
+        """
+            )
+        )
         result = testdir.runpytest()
         # Test order will be collection order; alphabetical
-        result.stdout.fnmatch_lines([
-            "test_a.py*",
-            "test_b.py*",
-        ])
+        result.stdout.fnmatch_lines(["test_a.py*", "test_b.py*"])
         result = testdir.runpytest("--ff")
         # Test order will be failing tests firs
-        result.stdout.fnmatch_lines([
-            "test_b.py*",
-            "test_a.py*",
-        ])
+        result.stdout.fnmatch_lines(["test_b.py*", "test_a.py*"])
 
     def test_lastfailed_failedfirst_order(self, testdir):
-        testdir.makepyfile(**{
-            'test_a.py': """
+        testdir.makepyfile(
+            **{
+                "test_a.py": """
                 def test_always_passes():
                     assert 1
             """,
-            'test_b.py': """
+                "test_b.py": """
                 def test_always_fails():
                     assert 0
             """,
-        })
+            }
+        )
         result = testdir.runpytest()
         # Test order will be collection order; alphabetical
-        result.stdout.fnmatch_lines([
-            "test_a.py*",
-            "test_b.py*",
-        ])
+        result.stdout.fnmatch_lines(["test_a.py*", "test_b.py*"])
         result = testdir.runpytest("--lf", "--ff")
         # Test order will be failing tests firs
-        result.stdout.fnmatch_lines([
-            "test_b.py*",
-        ])
-        assert 'test_a.py' not in result.stdout.str()
+        result.stdout.fnmatch_lines(["test_b.py*"])
+        assert "test_a.py" not in result.stdout.str()
 
     def test_lastfailed_difference_invocations(self, testdir, monkeypatch):
         monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", 1)
-        testdir.makepyfile(test_a="""
+        testdir.makepyfile(
+            test_a="""
             def test_a1():
                 assert 0
             def test_a2():
                 assert 1
-        """, test_b="""
+        """,
+            test_b="""
             def test_b1():
                 assert 0
-        """)
+        """,
+        )
         p = testdir.tmpdir.join("test_a.py")
         p2 = testdir.tmpdir.join("test_b.py")
 
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*2 failed*",
-        ])
+        result.stdout.fnmatch_lines(["*2 failed*"])
         result = testdir.runpytest("--lf", p2)
-        result.stdout.fnmatch_lines([
-            "*1 failed*",
-        ])
-        p2.write(_pytest._code.Source("""
+        result.stdout.fnmatch_lines(["*1 failed*"])
+        p2.write(
+            _pytest._code.Source(
+                """
             def test_b1():
                 assert 1
-        """))
+        """
+            )
+        )
         result = testdir.runpytest("--lf", p2)
-        result.stdout.fnmatch_lines([
-            "*1 passed*",
-        ])
+        result.stdout.fnmatch_lines(["*1 passed*"])
         result = testdir.runpytest("--lf", p)
-        result.stdout.fnmatch_lines([
-            "*1 failed*1 desel*",
-        ])
+        result.stdout.fnmatch_lines(["*1 failed*1 desel*"])
 
     def test_lastfailed_usecase_splice(self, testdir, monkeypatch):
         monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", 1)
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_1():
                 assert 0
-        """)
+        """
+        )
         p2 = testdir.tmpdir.join("test_something.py")
-        p2.write(_pytest._code.Source("""
+        p2.write(
+            _pytest._code.Source(
+                """
             def test_2():
                 assert 0
-        """))
+        """
+            )
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*2 failed*",
-        ])
+        result.stdout.fnmatch_lines(["*2 failed*"])
         result = testdir.runpytest("--lf", p2)
-        result.stdout.fnmatch_lines([
-            "*1 failed*",
-        ])
+        result.stdout.fnmatch_lines(["*1 failed*"])
         result = testdir.runpytest("--lf")
-        result.stdout.fnmatch_lines([
-            "*2 failed*",
-        ])
+        result.stdout.fnmatch_lines(["*2 failed*"])
 
     def test_lastfailed_xpass(self, testdir):
-        testdir.inline_runsource("""
+        testdir.inline_runsource(
+            """
             import pytest
             @pytest.mark.xfail
             def test_hello():
                 assert 1
-        """)
+        """
+        )
         config = testdir.parseconfigure()
         lastfailed = config.cache.get("cache/lastfailed", -1)
         assert lastfailed == -1
 
     def test_non_serializable_parametrize(self, testdir):
         """Test that failed parametrized tests with unmarshable parameters
         don't break pytest-cache.
         """
-        testdir.makepyfile(r"""
+        testdir.makepyfile(
+            r"""
             import pytest
 
             @pytest.mark.parametrize('val', [
                 b'\xac\x10\x02G',
             ])
             def test_fail(val):
                 assert False
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines('*1 failed in*')
+        result.stdout.fnmatch_lines("*1 failed in*")
 
     def test_terminal_report_lastfailed(self, testdir):
-        test_a = testdir.makepyfile(test_a="""
+        test_a = testdir.makepyfile(
+            test_a="""
             def test_a1():
                 pass
             def test_a2():
                 pass
-        """)
-        test_b = testdir.makepyfile(test_b="""
+        """
+        )
+        test_b = testdir.makepyfile(
+            test_b="""
             def test_b1():
                 assert 0
             def test_b2():
                 assert 0
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            'collected 4 items',
-            '*2 failed, 2 passed in*',
-        ])
+        result.stdout.fnmatch_lines(["collected 4 items", "*2 failed, 2 passed in*"])
 
-        result = testdir.runpytest('--lf')
-        result.stdout.fnmatch_lines([
-            'collected 4 items',
-            'run-last-failure: rerun previous 2 failures',
-            '*2 failed, 2 deselected in*',
-        ])
+        result = testdir.runpytest("--lf")
+        result.stdout.fnmatch_lines(
+            [
+                "collected 4 items / 2 deselected",
+                "run-last-failure: rerun previous 2 failures",
+                "*2 failed, 2 deselected in*",
+            ]
+        )
 
-        result = testdir.runpytest(test_a, '--lf')
-        result.stdout.fnmatch_lines([
-            'collected 2 items',
-            'run-last-failure: run all (no recorded failures)',
-            '*2 passed in*',
-        ])
+        result = testdir.runpytest(test_a, "--lf")
+        result.stdout.fnmatch_lines(
+            [
+                "collected 2 items",
+                "run-last-failure: run all (no recorded failures)",
+                "*2 passed in*",
+            ]
+        )
 
-        result = testdir.runpytest(test_b, '--lf')
-        result.stdout.fnmatch_lines([
-            'collected 2 items',
-            'run-last-failure: rerun previous 2 failures',
-            '*2 failed in*',
-        ])
+        result = testdir.runpytest(test_b, "--lf")
+        result.stdout.fnmatch_lines(
+            [
+                "collected 2 items",
+                "run-last-failure: rerun previous 2 failures",
+                "*2 failed in*",
+            ]
+        )
 
-        result = testdir.runpytest('test_b.py::test_b1', '--lf')
-        result.stdout.fnmatch_lines([
-            'collected 1 item',
-            'run-last-failure: rerun previous 1 failure',
-            '*1 failed in*',
-        ])
+        result = testdir.runpytest("test_b.py::test_b1", "--lf")
+        result.stdout.fnmatch_lines(
+            [
+                "collected 1 item",
+                "run-last-failure: rerun previous 1 failure",
+                "*1 failed in*",
+            ]
+        )
 
     def test_terminal_report_failedfirst(self, testdir):
-        testdir.makepyfile(test_a="""
+        testdir.makepyfile(
+            test_a="""
             def test_a1():
                 assert 0
             def test_a2():
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            'collected 2 items',
-            '*1 failed, 1 passed in*',
-        ])
+        result.stdout.fnmatch_lines(["collected 2 items", "*1 failed, 1 passed in*"])
 
-        result = testdir.runpytest('--ff')
-        result.stdout.fnmatch_lines([
-            'collected 2 items',
-            'run-last-failure: rerun previous 1 failure first',
-            '*1 failed, 1 passed in*',
-        ])
+        result = testdir.runpytest("--ff")
+        result.stdout.fnmatch_lines(
+            [
+                "collected 2 items",
+                "run-last-failure: rerun previous 1 failure first",
+                "*1 failed, 1 passed in*",
+            ]
+        )
 
     def test_lastfailed_collectfailure(self, testdir, monkeypatch):
 
-        testdir.makepyfile(test_maybe="""
-            import py
-            env = py.std.os.environ
+        testdir.makepyfile(
+            test_maybe="""
+            import os
+            env = os.environ
             if '1' == env['FAILIMPORT']:
                 raise ImportError('fail')
             def test_hello():
                 assert '0' == env['FAILTEST']
-        """)
+        """
+        )
 
         def rlf(fail_import, fail_run):
-            monkeypatch.setenv('FAILIMPORT', fail_import)
-            monkeypatch.setenv('FAILTEST', fail_run)
+            monkeypatch.setenv("FAILIMPORT", fail_import)
+            monkeypatch.setenv("FAILTEST", fail_run)
 
-            testdir.runpytest('-q')
+            testdir.runpytest("-q")
             config = testdir.parseconfigure()
             lastfailed = config.cache.get("cache/lastfailed", -1)
             return lastfailed
 
         lastfailed = rlf(fail_import=0, fail_run=0)
         assert lastfailed == -1
 
         lastfailed = rlf(fail_import=1, fail_run=0)
-        assert list(lastfailed) == ['test_maybe.py']
+        assert list(lastfailed) == ["test_maybe.py"]
 
         lastfailed = rlf(fail_import=0, fail_run=1)
-        assert list(lastfailed) == ['test_maybe.py::test_hello']
+        assert list(lastfailed) == ["test_maybe.py::test_hello"]
 
     def test_lastfailed_failure_subset(self, testdir, monkeypatch):
 
-        testdir.makepyfile(test_maybe="""
-            import py
-            env = py.std.os.environ
+        testdir.makepyfile(
+            test_maybe="""
+            import os
+            env = os.environ
             if '1' == env['FAILIMPORT']:
                 raise ImportError('fail')
             def test_hello():
                 assert '0' == env['FAILTEST']
-        """)
+        """
+        )
 
-        testdir.makepyfile(test_maybe2="""
-            import py
-            env = py.std.os.environ
+        testdir.makepyfile(
+            test_maybe2="""
+            import os
+            env = os.environ
             if '1' == env['FAILIMPORT']:
                 raise ImportError('fail')
             def test_hello():
                 assert '0' == env['FAILTEST']
 
             def test_pass():
                 pass
-        """)
+        """
+        )
 
         def rlf(fail_import, fail_run, args=()):
-            monkeypatch.setenv('FAILIMPORT', fail_import)
-            monkeypatch.setenv('FAILTEST', fail_run)
+            monkeypatch.setenv("FAILIMPORT", fail_import)
+            monkeypatch.setenv("FAILTEST", fail_run)
 
-            result = testdir.runpytest('-q', '--lf', *args)
+            result = testdir.runpytest("-q", "--lf", *args)
             config = testdir.parseconfigure()
             lastfailed = config.cache.get("cache/lastfailed", -1)
             return result, lastfailed
 
         result, lastfailed = rlf(fail_import=0, fail_run=0)
         assert lastfailed == -1
-        result.stdout.fnmatch_lines([
-            '*3 passed*',
-        ])
+        result.stdout.fnmatch_lines(["*3 passed*"])
 
         result, lastfailed = rlf(fail_import=1, fail_run=0)
-        assert sorted(list(lastfailed)) == ['test_maybe.py', 'test_maybe2.py']
+        assert sorted(list(lastfailed)) == ["test_maybe.py", "test_maybe2.py"]
 
-        result, lastfailed = rlf(fail_import=0, fail_run=0,
-                                 args=('test_maybe2.py',))
-        assert list(lastfailed) == ['test_maybe.py']
+        result, lastfailed = rlf(fail_import=0, fail_run=0, args=("test_maybe2.py",))
+        assert list(lastfailed) == ["test_maybe.py"]
 
         # edge case of test selection - even if we remember failures
         # from other tests we still need to run all tests if no test
         # matches the failures
-        result, lastfailed = rlf(fail_import=0, fail_run=0,
-                                 args=('test_maybe2.py',))
-        assert list(lastfailed) == ['test_maybe.py']
-        result.stdout.fnmatch_lines([
-            '*2 passed*',
-        ])
+        result, lastfailed = rlf(fail_import=0, fail_run=0, args=("test_maybe2.py",))
+        assert list(lastfailed) == ["test_maybe.py"]
+        result.stdout.fnmatch_lines(["*2 passed*"])
 
     def test_lastfailed_creates_cache_when_needed(self, testdir):
         # Issue #1342
-        testdir.makepyfile(test_empty='')
-        testdir.runpytest('-q', '--lf')
-        assert not os.path.exists('.cache')
+        testdir.makepyfile(test_empty="")
+        testdir.runpytest("-q", "--lf")
+        assert not os.path.exists(".pytest_cache/v/cache/lastfailed")
 
-        testdir.makepyfile(test_successful='def test_success():\n    assert True')
-        testdir.runpytest('-q', '--lf')
-        assert not os.path.exists('.cache')
+        testdir.makepyfile(test_successful="def test_success():\n    assert True")
+        testdir.runpytest("-q", "--lf")
+        assert not os.path.exists(".pytest_cache/v/cache/lastfailed")
 
-        testdir.makepyfile(test_errored='def test_error():\n    assert False')
-        testdir.runpytest('-q', '--lf')
-        assert os.path.exists('.cache')
+        testdir.makepyfile(test_errored="def test_error():\n    assert False")
+        testdir.runpytest("-q", "--lf")
+        assert os.path.exists(".pytest_cache/v/cache/lastfailed")
 
     def test_xfail_not_considered_failure(self, testdir):
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.xfail
             def test():
                 assert 0
-        ''')
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines('*1 xfailed*')
+        result.stdout.fnmatch_lines("*1 xfailed*")
         assert self.get_cached_last_failed(testdir) == []
 
     def test_xfail_strict_considered_failure(self, testdir):
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.xfail(strict=True)
             def test():
                 pass
-        ''')
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines('*1 failed*')
-        assert self.get_cached_last_failed(testdir) == ['test_xfail_strict_considered_failure.py::test']
+        result.stdout.fnmatch_lines("*1 failed*")
+        assert (
+            self.get_cached_last_failed(testdir)
+            == ["test_xfail_strict_considered_failure.py::test"]
+        )
 
-    @pytest.mark.parametrize('mark', ['mark.xfail', 'mark.skip'])
+    @pytest.mark.parametrize("mark", ["mark.xfail", "mark.skip"])
     def test_failed_changed_to_xfail_or_skip(self, testdir, mark):
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            """
             import pytest
             def test():
                 assert 0
-        ''')
+        """
+        )
         result = testdir.runpytest()
-        assert self.get_cached_last_failed(testdir) == ['test_failed_changed_to_xfail_or_skip.py::test']
+        assert (
+            self.get_cached_last_failed(testdir)
+            == ["test_failed_changed_to_xfail_or_skip.py::test"]
+        )
         assert result.ret == 1
 
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.{mark}
             def test():
                 assert 0
-        '''.format(mark=mark))
+        """.format(
+                mark=mark
+            )
+        )
         result = testdir.runpytest()
         assert result.ret == 0
         assert self.get_cached_last_failed(testdir) == []
         assert result.ret == 0
 
     def get_cached_last_failed(self, testdir):
         config = testdir.parseconfigure()
         return sorted(config.cache.get("cache/lastfailed", {}))
 
     def test_cache_cumulative(self, testdir):
         """
         Test workflow where user fixes errors gradually file by file using --lf.
         """
         # 1. initial run
-        test_bar = testdir.makepyfile(test_bar="""
+        test_bar = testdir.makepyfile(
+            test_bar="""
             def test_bar_1():
                 pass
             def test_bar_2():
                 assert 0
-        """)
-        test_foo = testdir.makepyfile(test_foo="""
+        """
+        )
+        test_foo = testdir.makepyfile(
+            test_foo="""
             def test_foo_3():
                 pass
             def test_foo_4():
                 assert 0
-        """)
+        """
+        )
         testdir.runpytest()
-        assert self.get_cached_last_failed(testdir) == ['test_bar.py::test_bar_2', 'test_foo.py::test_foo_4']
+        assert (
+            self.get_cached_last_failed(testdir)
+            == ["test_bar.py::test_bar_2", "test_foo.py::test_foo_4"]
+        )
 
         # 2. fix test_bar_2, run only test_bar.py
-        testdir.makepyfile(test_bar="""
+        testdir.makepyfile(
+            test_bar="""
             def test_bar_1():
                 pass
             def test_bar_2():
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest(test_bar)
-        result.stdout.fnmatch_lines('*2 passed*')
+        result.stdout.fnmatch_lines("*2 passed*")
         # ensure cache does not forget that test_foo_4 failed once before
-        assert self.get_cached_last_failed(testdir) == ['test_foo.py::test_foo_4']
+        assert self.get_cached_last_failed(testdir) == ["test_foo.py::test_foo_4"]
 
-        result = testdir.runpytest('--last-failed')
-        result.stdout.fnmatch_lines('*1 failed, 3 deselected*')
-        assert self.get_cached_last_failed(testdir) == ['test_foo.py::test_foo_4']
+        result = testdir.runpytest("--last-failed")
+        result.stdout.fnmatch_lines("*1 failed, 3 deselected*")
+        assert self.get_cached_last_failed(testdir) == ["test_foo.py::test_foo_4"]
 
         # 3. fix test_foo_4, run only test_foo.py
-        test_foo = testdir.makepyfile(test_foo="""
+        test_foo = testdir.makepyfile(
+            test_foo="""
             def test_foo_3():
                 pass
             def test_foo_4():
                 pass
-        """)
-        result = testdir.runpytest(test_foo, '--last-failed')
-        result.stdout.fnmatch_lines('*1 passed, 1 deselected*')
+        """
+        )
+        result = testdir.runpytest(test_foo, "--last-failed")
+        result.stdout.fnmatch_lines("*1 passed, 1 deselected*")
+        assert self.get_cached_last_failed(testdir) == []
+
+        result = testdir.runpytest("--last-failed")
+        result.stdout.fnmatch_lines("*4 passed*")
         assert self.get_cached_last_failed(testdir) == []
 
-        result = testdir.runpytest('--last-failed')
-        result.stdout.fnmatch_lines('*4 passed*')
-        assert self.get_cached_last_failed(testdir) == []
+    def test_lastfailed_no_failures_behavior_all_passed(self, testdir):
+        testdir.makepyfile(
+            """
+            def test_1():
+                assert True
+            def test_2():
+                assert True
+        """
+        )
+        result = testdir.runpytest()
+        result.stdout.fnmatch_lines(["*2 passed*"])
+        result = testdir.runpytest("--lf")
+        result.stdout.fnmatch_lines(["*2 passed*"])
+        result = testdir.runpytest("--lf", "--lfnf", "all")
+        result.stdout.fnmatch_lines(["*2 passed*"])
+        result = testdir.runpytest("--lf", "--lfnf", "none")
+        result.stdout.fnmatch_lines(["*2 desel*"])
+
+    def test_lastfailed_no_failures_behavior_empty_cache(self, testdir):
+        testdir.makepyfile(
+            """
+            def test_1():
+                assert True
+            def test_2():
+                assert False
+        """
+        )
+        result = testdir.runpytest("--lf", "--cache-clear")
+        result.stdout.fnmatch_lines(["*1 failed*1 passed*"])
+        result = testdir.runpytest("--lf", "--cache-clear", "--lfnf", "all")
+        result.stdout.fnmatch_lines(["*1 failed*1 passed*"])
+        result = testdir.runpytest("--lf", "--cache-clear", "--lfnf", "none")
+        result.stdout.fnmatch_lines(["*2 desel*"])
+
+
+class TestNewFirst(object):
+
+    def test_newfirst_usecase(self, testdir):
+        testdir.makepyfile(
+            **{
+                "test_1/test_1.py": """
+                def test_1(): assert 1
+                def test_2(): assert 1
+                def test_3(): assert 1
+            """,
+                "test_2/test_2.py": """
+                def test_1(): assert 1
+                def test_2(): assert 1
+                def test_3(): assert 1
+            """,
+            }
+        )
+
+        testdir.tmpdir.join("test_1/test_1.py").setmtime(1)
+
+        result = testdir.runpytest("-v")
+        result.stdout.fnmatch_lines(
+            [
+                "*test_1/test_1.py::test_1 PASSED*",
+                "*test_1/test_1.py::test_2 PASSED*",
+                "*test_1/test_1.py::test_3 PASSED*",
+                "*test_2/test_2.py::test_1 PASSED*",
+                "*test_2/test_2.py::test_2 PASSED*",
+                "*test_2/test_2.py::test_3 PASSED*",
+            ]
+        )
+
+        result = testdir.runpytest("-v", "--nf")
+
+        result.stdout.fnmatch_lines(
+            [
+                "*test_2/test_2.py::test_1 PASSED*",
+                "*test_2/test_2.py::test_2 PASSED*",
+                "*test_2/test_2.py::test_3 PASSED*",
+                "*test_1/test_1.py::test_1 PASSED*",
+                "*test_1/test_1.py::test_2 PASSED*",
+                "*test_1/test_1.py::test_3 PASSED*",
+            ]
+        )
+
+        testdir.tmpdir.join("test_1/test_1.py").write(
+            "def test_1(): assert 1\n"
+            "def test_2(): assert 1\n"
+            "def test_3(): assert 1\n"
+            "def test_4(): assert 1\n"
+        )
+        testdir.tmpdir.join("test_1/test_1.py").setmtime(1)
+
+        result = testdir.runpytest("-v", "--nf")
+
+        result.stdout.fnmatch_lines(
+            [
+                "*test_1/test_1.py::test_4 PASSED*",
+                "*test_2/test_2.py::test_1 PASSED*",
+                "*test_2/test_2.py::test_2 PASSED*",
+                "*test_2/test_2.py::test_3 PASSED*",
+                "*test_1/test_1.py::test_1 PASSED*",
+                "*test_1/test_1.py::test_2 PASSED*",
+                "*test_1/test_1.py::test_3 PASSED*",
+            ]
+        )
+
+    def test_newfirst_parametrize(self, testdir):
+        testdir.makepyfile(
+            **{
+                "test_1/test_1.py": """
+                import pytest
+                @pytest.mark.parametrize('num', [1, 2])
+                def test_1(num): assert num
+            """,
+                "test_2/test_2.py": """
+                import pytest
+                @pytest.mark.parametrize('num', [1, 2])
+                def test_1(num): assert num
+            """,
+            }
+        )
+
+        testdir.tmpdir.join("test_1/test_1.py").setmtime(1)
+
+        result = testdir.runpytest("-v")
+        result.stdout.fnmatch_lines(
+            [
+                "*test_1/test_1.py::test_1[1*",
+                "*test_1/test_1.py::test_1[2*",
+                "*test_2/test_2.py::test_1[1*",
+                "*test_2/test_2.py::test_1[2*",
+            ]
+        )
+
+        result = testdir.runpytest("-v", "--nf")
+
+        result.stdout.fnmatch_lines(
+            [
+                "*test_2/test_2.py::test_1[1*",
+                "*test_2/test_2.py::test_1[2*",
+                "*test_1/test_1.py::test_1[1*",
+                "*test_1/test_1.py::test_1[2*",
+            ]
+        )
+
+        testdir.tmpdir.join("test_1/test_1.py").write(
+            "import pytest\n"
+            "@pytest.mark.parametrize('num', [1, 2, 3])\n"
+            "def test_1(num): assert num\n"
+        )
+        testdir.tmpdir.join("test_1/test_1.py").setmtime(1)
+
+        result = testdir.runpytest("-v", "--nf")
+
+        result.stdout.fnmatch_lines(
+            [
+                "*test_1/test_1.py::test_1[3*",
+                "*test_2/test_2.py::test_1[1*",
+                "*test_2/test_2.py::test_1[2*",
+                "*test_1/test_1.py::test_1[1*",
+                "*test_1/test_1.py::test_1[2*",
+            ]
+        )
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_capture.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_capture.py
@@ -1,83 +1,76 @@
 from __future__ import absolute_import, division, print_function
+
 # note: py.io capture tests where copied from
 # pylib 1.4.20.dev2 (rev 13d9af95547e)
 from __future__ import with_statement
 import pickle
 import os
 import sys
 from io import UnsupportedOperation
 
 import _pytest._code
 import py
 import pytest
 import contextlib
-
+from six import binary_type, text_type
 from _pytest import capture
 from _pytest.capture import CaptureManager
 from _pytest.main import EXIT_NOTESTSCOLLECTED
 
 
 needsosdup = pytest.mark.xfail("not hasattr(os, 'dup')")
 
-if sys.version_info >= (3, 0):
-    def tobytes(obj):
-        if isinstance(obj, str):
-            obj = obj.encode('UTF-8')
-        assert isinstance(obj, bytes)
-        return obj
+
+def tobytes(obj):
+    if isinstance(obj, text_type):
+        obj = obj.encode("UTF-8")
+    assert isinstance(obj, binary_type)
+    return obj
 
-    def totext(obj):
-        if isinstance(obj, bytes):
-            obj = str(obj, 'UTF-8')
-        assert isinstance(obj, str)
-        return obj
-else:
-    def tobytes(obj):
-        if isinstance(obj, unicode):
-            obj = obj.encode('UTF-8')
-        assert isinstance(obj, str)
-        return obj
 
-    def totext(obj):
-        if isinstance(obj, str):
-            obj = unicode(obj, 'UTF-8')
-        assert isinstance(obj, unicode)
-        return obj
+def totext(obj):
+    if isinstance(obj, binary_type):
+        obj = text_type(obj, "UTF-8")
+    assert isinstance(obj, text_type)
+    return obj
 
 
 def oswritebytes(fd, obj):
     os.write(fd, tobytes(obj))
 
 
 def StdCaptureFD(out=True, err=True, in_=True):
     return capture.MultiCapture(out, err, in_, Capture=capture.FDCapture)
 
 
 def StdCapture(out=True, err=True, in_=True):
     return capture.MultiCapture(out, err, in_, Capture=capture.SysCapture)
 
 
 class TestCaptureManager(object):
+
     def test_getmethod_default_no_fd(self, monkeypatch):
         from _pytest.capture import pytest_addoption
-        from _pytest.config import Parser
+        from _pytest.config.argparsing import Parser
+
         parser = Parser()
         pytest_addoption(parser)
         default = parser._groups[0].options[0].default
         assert default == "fd" if hasattr(os, "dup") else "sys"
         parser = Parser()
-        monkeypatch.delattr(os, 'dup', raising=False)
+        monkeypatch.delattr(os, "dup", raising=False)
         pytest_addoption(parser)
         assert parser._groups[0].options[0].default == "sys"
 
     @needsosdup
-    @pytest.mark.parametrize("method",
-                             ['no', 'sys', pytest.mark.skipif('not hasattr(os, "dup")', 'fd')])
+    @pytest.mark.parametrize(
+        "method", ["no", "sys", pytest.mark.skipif('not hasattr(os, "dup")', "fd")]
+    )
     def test_capturing_basic_api(self, method):
         capouter = StdCaptureFD()
         old = sys.stdout, sys.stderr, sys.stdin
         try:
             capman = CaptureManager(method)
             capman.start_global_capturing()
             outerr = capman.suspend_global_capture()
             assert outerr == ("", "")
@@ -105,475 +98,534 @@ class TestCaptureManager(object):
             capman = CaptureManager("fd")
             capman.start_global_capturing()
             pytest.raises(AssertionError, "capman.start_global_capturing()")
             capman.stop_global_capturing()
         finally:
             capouter.stop_capturing()
 
 
-@pytest.mark.parametrize("method", ['fd', 'sys'])
+@pytest.mark.parametrize("method", ["fd", "sys"])
 def test_capturing_unicode(testdir, method):
     if hasattr(sys, "pypy_version_info") and sys.pypy_version_info < (2, 2):
         pytest.xfail("does not work on pypy < 2.2")
     if sys.version_info >= (3, 0):
         obj = "'b\u00f6y'"
     else:
         obj = "u'\u00f6y'"
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         # coding=utf8
         # taken from issue 227 from nosetests
         def test_unicode():
             import sys
             print (sys.stdout)
             print (%s)
-    """ % obj)
+    """
+        % obj
+    )
     result = testdir.runpytest("--capture=%s" % method)
-    result.stdout.fnmatch_lines([
-        "*1 passed*"
-    ])
+    result.stdout.fnmatch_lines(["*1 passed*"])
 
 
-@pytest.mark.parametrize("method", ['fd', 'sys'])
+@pytest.mark.parametrize("method", ["fd", "sys"])
 def test_capturing_bytes_in_utf8_encoding(testdir, method):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_unicode():
             print ('b\\u00f6y')
-    """)
+    """
+    )
     result = testdir.runpytest("--capture=%s" % method)
-    result.stdout.fnmatch_lines([
-        "*1 passed*"
-    ])
+    result.stdout.fnmatch_lines(["*1 passed*"])
 
 
 def test_collect_capturing(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         print ("collect %s failure" % 13)
         import xyz42123
-    """)
+    """
+    )
     result = testdir.runpytest(p)
-    result.stdout.fnmatch_lines([
-        "*Captured stdout*",
-        "*collect 13 failure*",
-    ])
+    result.stdout.fnmatch_lines(["*Captured stdout*", "*collect 13 failure*"])
 
 
 class TestPerTestCapturing(object):
+
     def test_capture_and_fixtures(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def setup_module(mod):
                 print ("setup module")
             def setup_function(function):
                 print ("setup " + function.__name__)
             def test_func1():
                 print ("in func1")
                 assert 0
             def test_func2():
                 print ("in func2")
                 assert 0
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            "setup module*",
-            "setup test_func1*",
-            "in func1*",
-            "setup test_func2*",
-            "in func2*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "setup module*",
+                "setup test_func1*",
+                "in func1*",
+                "setup test_func2*",
+                "in func2*",
+            ]
+        )
 
     @pytest.mark.xfail(reason="unimplemented feature")
     def test_capture_scope_cache(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import sys
             def setup_module(func):
                 print ("module-setup")
             def setup_function(func):
                 print ("function-setup")
             def test_func():
                 print ("in function")
                 assert 0
             def teardown_function(func):
                 print ("in teardown")
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            "*test_func():*",
-            "*Captured stdout during setup*",
-            "module-setup*",
-            "function-setup*",
-            "*Captured stdout*",
-            "in teardown*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*test_func():*",
+                "*Captured stdout during setup*",
+                "module-setup*",
+                "function-setup*",
+                "*Captured stdout*",
+                "in teardown*",
+            ]
+        )
 
     def test_no_carry_over(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_func1():
                 print ("in func1")
             def test_func2():
                 print ("in func2")
                 assert 0
-        """)
+        """
+        )
         result = testdir.runpytest(p)
         s = result.stdout.str()
         assert "in func1" not in s
         assert "in func2" in s
 
     def test_teardown_capturing(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def setup_function(function):
                 print ("setup func1")
             def teardown_function(function):
                 print ("teardown func1")
                 assert 0
             def test_func1():
                 print ("in func1")
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            '*teardown_function*',
-            '*Captured stdout*',
-            "setup func1*",
-            "in func1*",
-            "teardown func1*",
-            # "*1 fixture failure*"
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*teardown_function*",
+                "*Captured stdout*",
+                "setup func1*",
+                "in func1*",
+                "teardown func1*",
+                # "*1 fixture failure*"
+            ]
+        )
 
     def test_teardown_capturing_final(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def teardown_module(mod):
                 print ("teardown module")
                 assert 0
             def test_func():
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            "*def teardown_module(mod):*",
-            "*Captured stdout*",
-            "*teardown module*",
-            "*1 error*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*def teardown_module(mod):*",
+                "*Captured stdout*",
+                "*teardown module*",
+                "*1 error*",
+            ]
+        )
 
     def test_capturing_outerr(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             import sys
             def test_capturing():
                 print (42)
                 sys.stderr.write(str(23))
             def test_capturing_error():
                 print (1)
                 sys.stderr.write(str(2))
                 raise ValueError
-        """)
+        """
+        )
         result = testdir.runpytest(p1)
-        result.stdout.fnmatch_lines([
-            "*test_capturing_outerr.py .F*",
-            "====* FAILURES *====",
-            "____*____",
-            "*test_capturing_outerr.py:8: ValueError",
-            "*--- Captured stdout *call*",
-            "1",
-            "*--- Captured stderr *call*",
-            "2",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*test_capturing_outerr.py .F*",
+                "====* FAILURES *====",
+                "____*____",
+                "*test_capturing_outerr.py:8: ValueError",
+                "*--- Captured stdout *call*",
+                "1",
+                "*--- Captured stderr *call*",
+                "2",
+            ]
+        )
 
 
 class TestLoggingInteraction(object):
+
     def test_logging_stream_ownership(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_logging():
                 import logging
                 import pytest
                 stream = capture.CaptureIO()
                 logging.basicConfig(stream=stream)
                 stream.close() # to free memory/release resources
-        """)
+        """
+        )
         result = testdir.runpytest_subprocess(p)
         assert result.stderr.str().find("atexit") == -1
 
     def test_logging_and_immediate_setupteardown(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import logging
             def setup_function(function):
                 logging.warn("hello1")
 
             def test_logging():
                 logging.warn("hello2")
                 assert 0
 
             def teardown_function(function):
                 logging.warn("hello3")
                 assert 0
-        """)
-        for optargs in (('--capture=sys',), ('--capture=fd',)):
+        """
+        )
+        for optargs in (("--capture=sys",), ("--capture=fd",)):
             print(optargs)
             result = testdir.runpytest_subprocess(p, *optargs)
             s = result.stdout.str()
-            result.stdout.fnmatch_lines([
-                "*WARN*hello3",  # errors show first!
-                "*WARN*hello1",
-                "*WARN*hello2",
-            ])
+            result.stdout.fnmatch_lines(
+                ["*WARN*hello3", "*WARN*hello1", "*WARN*hello2"]  # errors show first!
+            )
             # verify proper termination
             assert "closed" not in s
 
     def test_logging_and_crossscope_fixtures(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import logging
             def setup_module(function):
                 logging.warn("hello1")
 
             def test_logging():
                 logging.warn("hello2")
                 assert 0
 
             def teardown_module(function):
                 logging.warn("hello3")
                 assert 0
-        """)
-        for optargs in (('--capture=sys',), ('--capture=fd',)):
+        """
+        )
+        for optargs in (("--capture=sys",), ("--capture=fd",)):
             print(optargs)
             result = testdir.runpytest_subprocess(p, *optargs)
             s = result.stdout.str()
-            result.stdout.fnmatch_lines([
-                "*WARN*hello3",  # errors come first
-                "*WARN*hello1",
-                "*WARN*hello2",
-            ])
+            result.stdout.fnmatch_lines(
+                ["*WARN*hello3", "*WARN*hello1", "*WARN*hello2"]  # errors come first
+            )
             # verify proper termination
             assert "closed" not in s
 
     def test_conftestlogging_is_shown(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
                 import logging
                 logging.basicConfig()
                 logging.warn("hello435")
-        """)
+        """
+        )
         # make sure that logging is still captured in tests
         result = testdir.runpytest_subprocess("-s", "-p", "no:capturelog")
         assert result.ret == EXIT_NOTESTSCOLLECTED
-        result.stderr.fnmatch_lines([
-            "WARNING*hello435*",
-        ])
-        assert 'operation on closed file' not in result.stderr.str()
+        result.stderr.fnmatch_lines(["WARNING*hello435*"])
+        assert "operation on closed file" not in result.stderr.str()
 
     def test_conftestlogging_and_test_logging(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
                 import logging
                 logging.basicConfig()
-        """)
+        """
+        )
         # make sure that logging is still captured in tests
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_hello():
                 import logging
                 logging.warn("hello433")
                 assert 0
-        """)
+        """
+        )
         result = testdir.runpytest_subprocess(p, "-p", "no:capturelog")
         assert result.ret != 0
-        result.stdout.fnmatch_lines([
-            "WARNING*hello433*",
-        ])
-        assert 'something' not in result.stderr.str()
-        assert 'operation on closed file' not in result.stderr.str()
+        result.stdout.fnmatch_lines(["WARNING*hello433*"])
+        assert "something" not in result.stderr.str()
+        assert "operation on closed file" not in result.stderr.str()
 
 
 class TestCaptureFixture(object):
+
     @pytest.mark.parametrize("opt", [[], ["-s"]])
     def test_std_functional(self, testdir, opt):
-        reprec = testdir.inline_runsource("""
+        reprec = testdir.inline_runsource(
+            """
             def test_hello(capsys):
                 print (42)
                 out, err = capsys.readouterr()
                 assert out.startswith("42")
-        """, *opt)
+        """,
+            *opt
+        )
         reprec.assertoutcome(passed=1)
 
     def test_capsyscapfd(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_one(capsys, capfd):
                 pass
             def test_two(capfd, capsys):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            "*ERROR*setup*test_one*",
-            "E*capfd*capsys*same*time*",
-            "*ERROR*setup*test_two*",
-            "E*capsys*capfd*same*time*",
-            "*2 error*"])
+        result.stdout.fnmatch_lines(
+            [
+                "*ERROR*setup*test_one*",
+                "E*capfd*capsys*same*time*",
+                "*ERROR*setup*test_two*",
+                "E*capsys*capfd*same*time*",
+                "*2 error*",
+            ]
+        )
 
     def test_capturing_getfixturevalue(self, testdir):
         """Test that asking for "capfd" and "capsys" using request.getfixturevalue
         in the same test is an error.
         """
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_one(capsys, request):
                 request.getfixturevalue("capfd")
             def test_two(capfd, request):
                 request.getfixturevalue("capsys")
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*test_one*",
-            "*capsys*capfd*same*time*",
-            "*test_two*",
-            "*capfd*capsys*same*time*",
-            "*2 failed in*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*test_one*",
+                "*capsys*capfd*same*time*",
+                "*test_two*",
+                "*capfd*capsys*same*time*",
+                "*2 failed in*",
+            ]
+        )
 
     def test_capsyscapfdbinary(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_one(capsys, capfdbinary):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            "*ERROR*setup*test_one*",
-            "E*capfdbinary*capsys*same*time*",
-            "*1 error*"])
+        result.stdout.fnmatch_lines(
+            ["*ERROR*setup*test_one*", "E*capfdbinary*capsys*same*time*", "*1 error*"]
+        )
 
     @pytest.mark.parametrize("method", ["sys", "fd"])
     def test_capture_is_represented_on_failure_issue128(self, testdir, method):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_hello(cap%s):
                 print ("xxx42xxx")
                 assert 0
-        """ % method)
+        """
+            % method
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            "xxx42xxx",
-        ])
+        result.stdout.fnmatch_lines(["xxx42xxx"])
 
     @needsosdup
     def test_stdfd_functional(self, testdir):
-        reprec = testdir.inline_runsource("""
+        reprec = testdir.inline_runsource(
+            """
             def test_hello(capfd):
                 import os
                 os.write(1, "42".encode('ascii'))
                 out, err = capfd.readouterr()
                 assert out.startswith("42")
                 capfd.close()
-        """)
+        """
+        )
         reprec.assertoutcome(passed=1)
 
     @needsosdup
     def test_capfdbinary(self, testdir):
-        reprec = testdir.inline_runsource("""
+        reprec = testdir.inline_runsource(
+            """
             def test_hello(capfdbinary):
                 import os
                 # some likely un-decodable bytes
                 os.write(1, b'\\xfe\\x98\\x20')
                 out, err = capfdbinary.readouterr()
                 assert out == b'\\xfe\\x98\\x20'
                 assert err == b''
-        """)
+        """
+        )
         reprec.assertoutcome(passed=1)
 
     @pytest.mark.skipif(
-        sys.version_info < (3,),
-        reason='only have capsysbinary in python 3',
+        sys.version_info < (3,), reason="only have capsysbinary in python 3"
     )
     def test_capsysbinary(self, testdir):
-        reprec = testdir.inline_runsource("""
+        reprec = testdir.inline_runsource(
+            """
             def test_hello(capsysbinary):
                 import sys
                 # some likely un-decodable bytes
                 sys.stdout.buffer.write(b'\\xfe\\x98\\x20')
                 out, err = capsysbinary.readouterr()
                 assert out == b'\\xfe\\x98\\x20'
                 assert err == b''
-        """)
+        """
+        )
         reprec.assertoutcome(passed=1)
 
     @pytest.mark.skipif(
-        sys.version_info >= (3,),
-        reason='only have capsysbinary in python 3',
+        sys.version_info >= (3,), reason="only have capsysbinary in python 3"
     )
     def test_capsysbinary_forbidden_in_python2(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_hello(capsysbinary):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*test_hello*",
-            "*capsysbinary is only supported on python 3*",
-            "*1 error in*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*test_hello*",
+                "*capsysbinary is only supported on python 3*",
+                "*1 error in*",
+            ]
+        )
 
     def test_partial_setup_failure(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_hello(capsys, missingarg):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            "*test_partial_setup_failure*",
-            "*1 error*",
-        ])
+        result.stdout.fnmatch_lines(["*test_partial_setup_failure*", "*1 error*"])
 
     @needsosdup
     def test_keyboardinterrupt_disables_capturing(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_hello(capfd):
                 import os
                 os.write(1, str(42).encode('ascii'))
                 raise KeyboardInterrupt()
-        """)
+        """
+        )
         result = testdir.runpytest_subprocess(p)
-        result.stdout.fnmatch_lines([
-            "*KeyboardInterrupt*"
-        ])
+        result.stdout.fnmatch_lines(["*KeyboardInterrupt*"])
         assert result.ret == 2
 
     @pytest.mark.issue14
     def test_capture_and_logging(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import logging
             def test_log(capsys):
                 logging.error('x')
-            """)
+            """
+        )
         result = testdir.runpytest_subprocess(p)
-        assert 'closed' not in result.stderr.str()
+        assert "closed" not in result.stderr.str()
 
-    @pytest.mark.parametrize('fixture', ['capsys', 'capfd'])
-    @pytest.mark.parametrize('no_capture', [True, False])
+    @pytest.mark.parametrize("fixture", ["capsys", "capfd"])
+    @pytest.mark.parametrize("no_capture", [True, False])
     def test_disabled_capture_fixture(self, testdir, fixture, no_capture):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_disabled({fixture}):
                 print('captured before')
                 with {fixture}.disabled():
                     print('while capture is disabled')
                 print('captured after')
                 assert {fixture}.readouterr() == ('captured before\\ncaptured after\\n', '')
 
             def test_normal():
                 print('test_normal executed')
-        """.format(fixture=fixture))
-        args = ('-s',) if no_capture else ()
+        """.format(
+                fixture=fixture
+            )
+        )
+        args = ("-s",) if no_capture else ()
         result = testdir.runpytest_subprocess(*args)
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *while capture is disabled*
-        """)
-        assert 'captured before' not in result.stdout.str()
-        assert 'captured after' not in result.stdout.str()
+        """
+        )
+        assert "captured before" not in result.stdout.str()
+        assert "captured after" not in result.stdout.str()
         if no_capture:
-            assert 'test_normal executed' in result.stdout.str()
+            assert "test_normal executed" in result.stdout.str()
         else:
-            assert 'test_normal executed' not in result.stdout.str()
+            assert "test_normal executed" not in result.stdout.str()
 
-    @pytest.mark.parametrize('fixture', ['capsys', 'capfd'])
+    @pytest.mark.parametrize("fixture", ["capsys", "capfd"])
     def test_fixture_use_by_other_fixtures(self, testdir, fixture):
         """
         Ensure that capsys and capfd can be used by other fixtures during setup and teardown.
         """
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             from __future__ import print_function
             import sys
             import pytest
 
             @pytest.fixture
             def captured_print({fixture}):
                 print('stdout contents begin')
                 print('stderr contents begin', file=sys.stderr)
@@ -586,206 +638,223 @@ class TestCaptureFixture(object):
                 out, err = {fixture}.readouterr()
                 assert out == 'stdout contents end\\n'
                 assert err == 'stderr contents end\\n'
 
             def test_captured_print(captured_print):
                 out, err = captured_print
                 assert out == 'stdout contents begin\\n'
                 assert err == 'stderr contents begin\\n'
-        """.format(fixture=fixture))
+        """.format(
+                fixture=fixture
+            )
+        )
         result = testdir.runpytest_subprocess()
         result.stdout.fnmatch_lines("*1 passed*")
-        assert 'stdout contents begin' not in result.stdout.str()
-        assert 'stderr contents begin' not in result.stdout.str()
+        assert "stdout contents begin" not in result.stdout.str()
+        assert "stderr contents begin" not in result.stdout.str()
 
 
 def test_setup_failure_does_not_kill_capturing(testdir):
     sub1 = testdir.mkpydir("sub1")
-    sub1.join("conftest.py").write(_pytest._code.Source("""
+    sub1.join("conftest.py").write(
+        _pytest._code.Source(
+            """
         def pytest_runtest_setup(item):
             raise ValueError(42)
-    """))
+    """
+        )
+    )
     sub1.join("test_mod.py").write("def test_func1(): pass")
-    result = testdir.runpytest(testdir.tmpdir, '--traceconfig')
-    result.stdout.fnmatch_lines([
-        "*ValueError(42)*",
-        "*1 error*"
-    ])
+    result = testdir.runpytest(testdir.tmpdir, "--traceconfig")
+    result.stdout.fnmatch_lines(["*ValueError(42)*", "*1 error*"])
 
 
 def test_fdfuncarg_skips_on_no_osdup(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import os
         if hasattr(os, 'dup'):
             del os.dup
         def test_hello(capfd):
             pass
-    """)
+    """
+    )
     result = testdir.runpytest_subprocess("--capture=no")
-    result.stdout.fnmatch_lines([
-        "*1 skipped*"
-    ])
+    result.stdout.fnmatch_lines(["*1 skipped*"])
 
 
 def test_capture_conftest_runtest_setup(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         def pytest_runtest_setup():
             print ("hello19")
-    """)
+    """
+    )
     testdir.makepyfile("def test_func(): pass")
     result = testdir.runpytest()
     assert result.ret == 0
-    assert 'hello19' not in result.stdout.str()
+    assert "hello19" not in result.stdout.str()
 
 
 def test_capture_badoutput_issue412(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import os
 
         def test_func():
             omg = bytearray([1,129,1])
             os.write(1, omg)
             assert 0
-        """)
-    result = testdir.runpytest('--cap=fd')
-    result.stdout.fnmatch_lines('''
+        """
+    )
+    result = testdir.runpytest("--cap=fd")
+    result.stdout.fnmatch_lines(
+        """
         *def test_func*
         *assert 0*
         *Captured*
         *1 failed*
-    ''')
+    """
+    )
 
 
 def test_capture_early_option_parsing(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         def pytest_runtest_setup():
             print ("hello19")
-    """)
+    """
+    )
     testdir.makepyfile("def test_func(): pass")
     result = testdir.runpytest("-vs")
     assert result.ret == 0
-    assert 'hello19' in result.stdout.str()
+    assert "hello19" in result.stdout.str()
 
 
 def test_capture_binary_output(testdir):
-    testdir.makepyfile(r"""
+    testdir.makepyfile(
+        r"""
         import pytest
 
         def test_a():
             import sys
             import subprocess
             subprocess.call([sys.executable, __file__])
 
         def test_foo():
             import os;os.write(1, b'\xc3')
 
         if __name__ == '__main__':
             test_foo()
-        """)
-    result = testdir.runpytest('--assert=plain')
+        """
+    )
+    result = testdir.runpytest("--assert=plain")
     result.assert_outcomes(passed=2)
 
 
 def test_error_during_readouterr(testdir):
     """Make sure we suspend capturing if errors occur during readouterr"""
-    testdir.makepyfile(pytest_xyz="""
+    testdir.makepyfile(
+        pytest_xyz="""
         from _pytest.capture import FDCapture
         def bad_snap(self):
             raise Exception('boom')
         assert FDCapture.snap
         FDCapture.snap = bad_snap
-    """)
+    """
+    )
     result = testdir.runpytest_subprocess(
         "-p", "pytest_xyz", "--version", syspathinsert=True
     )
-    result.stderr.fnmatch_lines([
-        "*in bad_snap",
-        "    raise Exception('boom')",
-        "Exception: boom",
-    ])
+    result.stderr.fnmatch_lines(
+        ["*in bad_snap", "    raise Exception('boom')", "Exception: boom"]
+    )
 
 
 class TestCaptureIO(object):
+
     def test_text(self):
         f = capture.CaptureIO()
         f.write("hello")
         s = f.getvalue()
         assert s == "hello"
         f.close()
 
     def test_unicode_and_str_mixture(self):
         f = capture.CaptureIO()
         if sys.version_info >= (3, 0):
             f.write("\u00f6")
             pytest.raises(TypeError, "f.write(bytes('hello', 'UTF-8'))")
         else:
-            f.write(unicode("\u00f6", 'UTF-8'))
+            f.write(text_type("\u00f6", "UTF-8"))
             f.write("hello")  # bytes
             s = f.getvalue()
             f.close()
-            assert isinstance(s, unicode)
+            assert isinstance(s, text_type)
 
-    @pytest.mark.skipif(
-        sys.version_info[0] == 2,
-        reason='python 3 only behaviour',
-    )
+    @pytest.mark.skipif(sys.version_info[0] == 2, reason="python 3 only behaviour")
     def test_write_bytes_to_buffer(self):
         """In python3, stdout / stderr are text io wrappers (exposing a buffer
         property of the underlying bytestream).  See issue #1407
         """
         f = capture.CaptureIO()
-        f.buffer.write(b'foo\r\n')
-        assert f.getvalue() == 'foo\r\n'
+        f.buffer.write(b"foo\r\n")
+        assert f.getvalue() == "foo\r\n"
 
 
 def test_bytes_io():
     f = py.io.BytesIO()
     f.write(tobytes("hello"))
     pytest.raises(TypeError, "f.write(totext('hello'))")
     s = f.getvalue()
     assert s == tobytes("hello")
 
 
 def test_dontreadfrominput():
     from _pytest.capture import DontReadFromInput
+
     f = DontReadFromInput()
     assert not f.isatty()
     pytest.raises(IOError, f.read)
     pytest.raises(IOError, f.readlines)
-    pytest.raises(IOError, iter, f)
+    iter_f = iter(f)
+    pytest.raises(IOError, next, iter_f)
     pytest.raises(UnsupportedOperation, f.fileno)
     f.close()  # just for completeness
 
 
-@pytest.mark.skipif('sys.version_info < (3,)', reason='python2 has no buffer')
+@pytest.mark.skipif("sys.version_info < (3,)", reason="python2 has no buffer")
 def test_dontreadfrominput_buffer_python3():
     from _pytest.capture import DontReadFromInput
+
     f = DontReadFromInput()
     fb = f.buffer
     assert not fb.isatty()
     pytest.raises(IOError, fb.read)
     pytest.raises(IOError, fb.readlines)
-    pytest.raises(IOError, iter, fb)
+    iter_f = iter(f)
+    pytest.raises(IOError, next, iter_f)
     pytest.raises(ValueError, fb.fileno)
     f.close()  # just for completeness
 
 
-@pytest.mark.skipif('sys.version_info >= (3,)', reason='python2 has no buffer')
+@pytest.mark.skipif("sys.version_info >= (3,)", reason="python2 has no buffer")
 def test_dontreadfrominput_buffer_python2():
     from _pytest.capture import DontReadFromInput
+
     f = DontReadFromInput()
     with pytest.raises(AttributeError):
         f.buffer
     f.close()  # just for completeness
 
 
 @pytest.yield_fixture
 def tmpfile(testdir):
-    f = testdir.makepyfile("").open('wb+')
+    f = testdir.makepyfile("").open("wb+")
     yield f
     if not f.closed:
         f.close()
 
 
 @needsosdup
 def test_dupfile(tmpfile):
     flist = []
@@ -813,25 +882,25 @@ def test_dupfile(tmpfile):
     assert fname_closed == repr(flist[0].buffer)
 
 
 def test_dupfile_on_bytesio():
     io = py.io.BytesIO()
     f = capture.safe_text_dupfile(io, "wb")
     f.write("hello")
     assert io.getvalue() == b"hello"
-    assert 'BytesIO object' in f.name
+    assert "BytesIO object" in f.name
 
 
 def test_dupfile_on_textio():
     io = py.io.TextIO()
     f = capture.safe_text_dupfile(io, "wb")
     f.write("hello")
     assert io.getvalue() == "hello"
-    assert not hasattr(f, 'name')
+    assert not hasattr(f, "name")
 
 
 @contextlib.contextmanager
 def lsof_check():
     pid = os.getpid()
     try:
         out = py.process.cmdexec("lsof -p %d" % pid)
     except (py.process.cmdexec.Error, UnicodeDecodeError):
@@ -863,17 +932,17 @@ class TestFDCapture(object):
         assert s == "hello"
 
     def test_simple_many(self, tmpfile):
         for i in range(10):
             self.test_simple(tmpfile)
 
     def test_simple_many_check_open_files(self, testdir):
         with lsof_check():
-            with testdir.makepyfile("").open('wb+') as tmpfile:
+            with testdir.makepyfile("").open("wb+") as tmpfile:
                 self.test_simple_many(tmpfile)
 
     def test_simple_fail_second_start(self, tmpfile):
         fd = tmpfile.fileno()
         cap = capture.FDCapture(fd)
         cap.done()
         pytest.raises(ValueError, cap.start)
 
@@ -885,29 +954,29 @@ class TestFDCapture(object):
         cap.done()
         assert s == "hello\n"
 
     def test_stdin(self, tmpfile):
         cap = capture.FDCapture(0)
         cap.start()
         x = os.read(0, 100).strip()
         cap.done()
-        assert x == tobytes('')
+        assert x == tobytes("")
 
     def test_writeorg(self, tmpfile):
         data1, data2 = tobytes("foo"), tobytes("bar")
         cap = capture.FDCapture(tmpfile.fileno())
         cap.start()
         tmpfile.write(data1)
         tmpfile.flush()
         cap.writeorg(data2)
         scap = cap.snap()
         cap.done()
         assert scap == totext(data1)
-        with open(tmpfile.name, 'rb') as stmp_file:
+        with open(tmpfile.name, "rb") as stmp_file:
             stmp = stmp_file.read()
             assert stmp == data2
 
     def test_simple_resume_suspend(self, tmpfile):
         with saved_fd(1):
             cap = capture.FDCapture(1)
             cap.start()
             data = tobytes("hello")
@@ -987,24 +1056,25 @@ class TestStdCapture(object):
         assert capture_result.err == "world"
 
     def test_capturing_readouterr_unicode(self):
         with self.getcapture() as cap:
             print("hx\xc4\x85\xc4\x87")
             out, err = cap.readouterr()
         assert out == py.builtin._totext("hx\xc4\x85\xc4\x87\n", "utf8")
 
-    @pytest.mark.skipif('sys.version_info >= (3,)',
-                        reason='text output different for bytes on python3')
+    @pytest.mark.skipif(
+        "sys.version_info >= (3,)", reason="text output different for bytes on python3"
+    )
     def test_capturing_readouterr_decode_error_handling(self):
         with self.getcapture() as cap:
-            # triggered a internal error in pytest
-            print('\xa6')
+            # triggered an internal error in pytest
+            print("\xa6")
             out, err = cap.readouterr()
-        assert out == py.builtin._totext('\ufffd\n', 'unicode-escape')
+        assert out == py.builtin._totext("\ufffd\n", "unicode-escape")
 
     def test_reset_twice_error(self):
         with self.getcapture() as cap:
             print("hello")
             out, err = cap.readouterr()
         pytest.raises(ValueError, cap.stop_capturing)
         assert out == "hello\n"
         assert not err
@@ -1066,28 +1136,32 @@ class TestStdCapture(object):
             pytest.raises(IOError, "sys.stdin.read()")
 
 
 class TestStdCaptureFD(TestStdCapture):
     pytestmark = needsosdup
     captureclass = staticmethod(StdCaptureFD)
 
     def test_simple_only_fd(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import os
             def test_x():
                 os.write(1, "hello\\n".encode("ascii"))
                 assert 0
-        """)
+        """
+        )
         result = testdir.runpytest_subprocess()
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *test_x*
             *assert 0*
             *Captured stdout*
-        """)
+        """
+        )
 
     def test_intermingling(self):
         with self.getcapture() as cap:
             oswritebytes(1, "1")
             sys.stdout.write(str(2))
             sys.stdout.flush()
             oswritebytes(1, "3")
             oswritebytes(2, "a")
@@ -1104,17 +1178,18 @@ class TestStdCaptureFD(TestStdCapture):
                 cap = StdCaptureFD()
                 cap.stop_capturing()
 
 
 class TestStdCaptureFDinvalidFD(object):
     pytestmark = needsosdup
 
     def test_stdcapture_fd_invalid_fd(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import os
             from _pytest import capture
             def StdCaptureFD(out=True, err=True, in_=True):
                 return capture.MultiCapture(out, err, in_,
                                               Capture=capture.FDCapture)
             def test_stdout():
                 os.close(1)
                 cap = StdCaptureFD(out=True, err=False, in_=False)
@@ -1122,85 +1197,91 @@ class TestStdCaptureFDinvalidFD(object):
             def test_stderr():
                 os.close(2)
                 cap = StdCaptureFD(out=False, err=True, in_=False)
                 cap.stop_capturing()
             def test_stdin():
                 os.close(0)
                 cap = StdCaptureFD(out=False, err=False, in_=True)
                 cap.stop_capturing()
-        """)
+        """
+        )
         result = testdir.runpytest_subprocess("--capture=fd")
         assert result.ret == 0
-        assert result.parseoutcomes()['passed'] == 3
+        assert result.parseoutcomes()["passed"] == 3
 
 
 def test_capture_not_started_but_reset():
     capsys = StdCapture()
     capsys.stop_capturing()
 
 
 def test_using_capsys_fixture_works_with_sys_stdout_encoding(capsys):
-    test_text = 'test text'
+    test_text = "test text"
 
-    print(test_text.encode(sys.stdout.encoding, 'replace'))
+    print(test_text.encode(sys.stdout.encoding, "replace"))
     (out, err) = capsys.readouterr()
     assert out
-    assert err == ''
+    assert err == ""
 
 
 def test_capsys_results_accessible_by_attribute(capsys):
     sys.stdout.write("spam")
     sys.stderr.write("eggs")
     capture_result = capsys.readouterr()
     assert capture_result.out == "spam"
     assert capture_result.err == "eggs"
 
 
 @needsosdup
-@pytest.mark.parametrize('use', [True, False])
+@pytest.mark.parametrize("use", [True, False])
 def test_fdcapture_tmpfile_remains_the_same(tmpfile, use):
     if not use:
         tmpfile = True
     cap = StdCaptureFD(out=False, err=tmpfile)
     try:
         cap.start_capturing()
         capfile = cap.err.tmpfile
         cap.readouterr()
     finally:
         cap.stop_capturing()
     capfile2 = cap.err.tmpfile
     assert capfile2 == capfile
 
 
 @needsosdup
 def test_close_and_capture_again(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import os
         def test_close():
             os.close(1)
         def test_capture_again():
             os.write(1, b"hello\\n")
             assert 0
-    """)
+    """
+    )
     result = testdir.runpytest_subprocess()
-    result.stdout.fnmatch_lines("""
+    result.stdout.fnmatch_lines(
+        """
         *test_capture_again*
         *assert 0*
         *stdout*
         *hello*
-    """)
+    """
+    )
 
 
-@pytest.mark.parametrize('method', ['SysCapture', 'FDCapture'])
+@pytest.mark.parametrize("method", ["SysCapture", "FDCapture"])
 def test_capturing_and_logging_fundamentals(testdir, method):
-    if method == "StdCaptureFD" and not hasattr(os, 'dup'):
+    if method == "StdCaptureFD" and not hasattr(os, "dup"):
         pytest.skip("need os.dup")
     # here we check a fundamental feature
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         import sys, os
         import py, logging
         from _pytest import capture
         cap = capture.MultiCapture(out=False, in_=False,
                                      Capture=capture.%s)
         cap.start_capturing()
 
         logging.warn("hello1")
@@ -1208,67 +1289,106 @@ def test_capturing_and_logging_fundament
         print ("suspend, captured %%s" %%(outerr,))
         logging.warn("hello2")
 
         cap.pop_outerr_to_orig()
         logging.warn("hello3")
 
         outerr = cap.readouterr()
         print ("suspend2, captured %%s" %% (outerr,))
-    """ % (method,))
+    """
+        % (method,)
+    )
     result = testdir.runpython(p)
-    result.stdout.fnmatch_lines("""
+    result.stdout.fnmatch_lines(
+        """
         suspend, captured*hello1*
         suspend2, captured*WARNING:root:hello3*
-    """)
-    result.stderr.fnmatch_lines("""
+    """
+    )
+    result.stderr.fnmatch_lines(
+        """
         WARNING:root:hello2
-    """)
+    """
+    )
     assert "atexit" not in result.stderr.str()
 
 
 def test_error_attribute_issue555(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import sys
         def test_capattr():
             assert sys.stdout.errors == "strict"
             assert sys.stderr.errors == "strict"
-    """)
+    """
+    )
     reprec = testdir.inline_run()
     reprec.assertoutcome(passed=1)
 
 
-@pytest.mark.skipif(not sys.platform.startswith('win') and sys.version_info[:2] >= (3, 6),
-                    reason='only py3.6+ on windows')
+@pytest.mark.skipif(
+    not sys.platform.startswith("win") and sys.version_info[:2] >= (3, 6),
+    reason="only py3.6+ on windows",
+)
 def test_py36_windowsconsoleio_workaround_non_standard_streams():
     """
     Ensure _py36_windowsconsoleio_workaround function works with objects that
     do not implement the full ``io``-based stream protocol, for example execnet channels (#2666).
     """
     from _pytest.capture import _py36_windowsconsoleio_workaround
 
-    class DummyStream:
+    class DummyStream(object):
+
         def write(self, s):
             pass
 
     stream = DummyStream()
     _py36_windowsconsoleio_workaround(stream)
 
 
 def test_dontreadfrominput_has_encoding(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import sys
         def test_capattr():
             # should not raise AttributeError
             assert sys.stdout.encoding
             assert sys.stderr.encoding
-    """)
+    """
+    )
     reprec = testdir.inline_run()
     reprec.assertoutcome(passed=1)
 
 
+def test_crash_on_closing_tmpfile_py27(testdir):
+    testdir.makepyfile(
+        """
+        from __future__ import print_function
+        import time
+        import threading
+        import sys
+
+        def spam():
+            f = sys.stderr
+            while True:
+                print('.', end='', file=f)
+
+        def test_silly():
+            t = threading.Thread(target=spam)
+            t.daemon = True
+            t.start()
+            time.sleep(0.5)
+
+    """
+    )
+    result = testdir.runpytest_subprocess()
+    assert result.ret == 0
+    assert "IOError" not in result.stdout.str()
+
+
 def test_pickling_and_unpickling_encoded_file():
     # See https://bitbucket.org/pytest-dev/pytest/pull-request/194
     # pickle.loads() raises infinite recursion if
     # EncodedFile.__getattr__ is not implemented properly
     ef = capture.EncodedFile(None, None)
     ef_as_str = pickle.dumps(ef)
     pickle.loads(ef_as_str)
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_collection.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_collection.py
@@ -1,398 +1,448 @@
 from __future__ import absolute_import, division, print_function
+import pprint
+import sys
 import pytest
-import py
 
 import _pytest._code
 from _pytest.main import Session, EXIT_NOTESTSCOLLECTED, _in_venv
 
 
 class TestCollector(object):
+
     def test_collect_versus_item(self):
         from pytest import Collector, Item
+
         assert not issubclass(Collector, Item)
         assert not issubclass(Item, Collector)
 
     def test_compat_attributes(self, testdir, recwarn):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             def test_pass(): pass
             def test_fail(): assert 0
-        """)
+        """
+        )
         recwarn.clear()
         assert modcol.Module == pytest.Module
         assert modcol.Class == pytest.Class
         assert modcol.Item == pytest.Item
         assert modcol.File == pytest.File
         assert modcol.Function == pytest.Function
 
     def test_check_equality(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             def test_pass(): pass
             def test_fail(): assert 0
-        """)
+        """
+        )
         fn1 = testdir.collect_by_name(modcol, "test_pass")
         assert isinstance(fn1, pytest.Function)
         fn2 = testdir.collect_by_name(modcol, "test_pass")
         assert isinstance(fn2, pytest.Function)
 
         assert fn1 == fn2
         assert fn1 != modcol
-        if py.std.sys.version_info < (3, 0):
-            assert cmp(fn1, fn2) == 0
+        if sys.version_info < (3, 0):
+            assert cmp(fn1, fn2) == 0  # NOQA
         assert hash(fn1) == hash(fn2)
 
         fn3 = testdir.collect_by_name(modcol, "test_fail")
         assert isinstance(fn3, pytest.Function)
         assert not (fn1 == fn3)
         assert fn1 != fn3
 
         for fn in fn1, fn2, fn3:
             assert fn != 3
             assert fn != modcol
             assert fn != [1, 2, 3]
             assert [1, 2, 3] != fn
             assert modcol != fn
 
     def test_getparent(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             class TestClass(object):
                  def test_foo():
                      pass
-        """)
+        """
+        )
         cls = testdir.collect_by_name(modcol, "TestClass")
-        fn = testdir.collect_by_name(
-            testdir.collect_by_name(cls, "()"), "test_foo")
+        fn = testdir.collect_by_name(testdir.collect_by_name(cls, "()"), "test_foo")
 
         parent = fn.getparent(pytest.Module)
         assert parent is modcol
 
         parent = fn.getparent(pytest.Function)
         assert parent is fn
 
         parent = fn.getparent(pytest.Class)
         assert parent is cls
 
     def test_getcustomfile_roundtrip(self, testdir):
         hello = testdir.makefile(".xxx", hello="world")
-        testdir.makepyfile(conftest="""
+        testdir.makepyfile(
+            conftest="""
             import pytest
             class CustomFile(pytest.File):
                 pass
             def pytest_collect_file(path, parent):
                 if path.ext == ".xxx":
                     return CustomFile(path, parent=parent)
-        """)
+        """
+        )
         node = testdir.getpathnode(hello)
         assert isinstance(node, pytest.File)
         assert node.name == "hello.xxx"
         nodes = node.session.perform_collect([node.nodeid], genitems=False)
         assert len(nodes) == 1
         assert isinstance(nodes[0], pytest.File)
 
     def test_can_skip_class_with_test_attr(self, testdir):
         """Assure test class is skipped when using `__test__=False` (See #2007)."""
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             class TestFoo(object):
                 __test__ = False
                 def __init__(self):
                     pass
                 def test_foo():
                     assert True
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            'collected 0 items',
-            '*no tests ran in*',
-        ])
+        result.stdout.fnmatch_lines(["collected 0 items", "*no tests ran in*"])
 
 
 class TestCollectFS(object):
+
     def test_ignored_certain_directories(self, testdir):
         tmpdir = testdir.tmpdir
-        tmpdir.ensure("build", 'test_notfound.py')
-        tmpdir.ensure("dist", 'test_notfound.py')
-        tmpdir.ensure("_darcs", 'test_notfound.py')
-        tmpdir.ensure("CVS", 'test_notfound.py')
-        tmpdir.ensure("{arch}", 'test_notfound.py')
-        tmpdir.ensure(".whatever", 'test_notfound.py')
-        tmpdir.ensure(".bzr", 'test_notfound.py')
-        tmpdir.ensure("normal", 'test_found.py')
+        tmpdir.ensure("build", "test_notfound.py")
+        tmpdir.ensure("dist", "test_notfound.py")
+        tmpdir.ensure("_darcs", "test_notfound.py")
+        tmpdir.ensure("CVS", "test_notfound.py")
+        tmpdir.ensure("{arch}", "test_notfound.py")
+        tmpdir.ensure(".whatever", "test_notfound.py")
+        tmpdir.ensure(".bzr", "test_notfound.py")
+        tmpdir.ensure("normal", "test_found.py")
         for x in tmpdir.visit("test_*.py"):
             x.write("def test_hello(): pass")
 
         result = testdir.runpytest("--collect-only")
         s = result.stdout.str()
         assert "test_notfound" not in s
         assert "test_found" in s
 
-    @pytest.mark.parametrize('fname',
-                             ("activate", "activate.csh", "activate.fish",
-                              "Activate", "Activate.bat", "Activate.ps1"))
+    @pytest.mark.parametrize(
+        "fname",
+        (
+            "activate",
+            "activate.csh",
+            "activate.fish",
+            "Activate",
+            "Activate.bat",
+            "Activate.ps1",
+        ),
+    )
     def test_ignored_virtualenvs(self, testdir, fname):
-        bindir = "Scripts" if py.std.sys.platform.startswith("win") else "bin"
+        bindir = "Scripts" if sys.platform.startswith("win") else "bin"
         testdir.tmpdir.ensure("virtual", bindir, fname)
         testfile = testdir.tmpdir.ensure("virtual", "test_invenv.py")
         testfile.write("def test_hello(): pass")
 
         # by default, ignore tests inside a virtualenv
         result = testdir.runpytest()
         assert "test_invenv" not in result.stdout.str()
         # allow test collection if user insists
         result = testdir.runpytest("--collect-in-virtualenv")
         assert "test_invenv" in result.stdout.str()
         # allow test collection if user directly passes in the directory
         result = testdir.runpytest("virtual")
         assert "test_invenv" in result.stdout.str()
 
-    @pytest.mark.parametrize('fname',
-                             ("activate", "activate.csh", "activate.fish",
-                              "Activate", "Activate.bat", "Activate.ps1"))
+    @pytest.mark.parametrize(
+        "fname",
+        (
+            "activate",
+            "activate.csh",
+            "activate.fish",
+            "Activate",
+            "Activate.bat",
+            "Activate.ps1",
+        ),
+    )
     def test_ignored_virtualenvs_norecursedirs_precedence(self, testdir, fname):
-        bindir = "Scripts" if py.std.sys.platform.startswith("win") else "bin"
+        bindir = "Scripts" if sys.platform.startswith("win") else "bin"
         # norecursedirs takes priority
         testdir.tmpdir.ensure(".virtual", bindir, fname)
         testfile = testdir.tmpdir.ensure(".virtual", "test_invenv.py")
         testfile.write("def test_hello(): pass")
         result = testdir.runpytest("--collect-in-virtualenv")
         assert "test_invenv" not in result.stdout.str()
         # ...unless the virtualenv is explicitly given on the CLI
         result = testdir.runpytest("--collect-in-virtualenv", ".virtual")
         assert "test_invenv" in result.stdout.str()
 
-    @pytest.mark.parametrize('fname',
-                             ("activate", "activate.csh", "activate.fish",
-                              "Activate", "Activate.bat", "Activate.ps1"))
+    @pytest.mark.parametrize(
+        "fname",
+        (
+            "activate",
+            "activate.csh",
+            "activate.fish",
+            "Activate",
+            "Activate.bat",
+            "Activate.ps1",
+        ),
+    )
     def test__in_venv(self, testdir, fname):
         """Directly test the virtual env detection function"""
-        bindir = "Scripts" if py.std.sys.platform.startswith("win") else "bin"
+        bindir = "Scripts" if sys.platform.startswith("win") else "bin"
         # no bin/activate, not a virtualenv
-        base_path = testdir.tmpdir.mkdir('venv')
+        base_path = testdir.tmpdir.mkdir("venv")
         assert _in_venv(base_path) is False
         # with bin/activate, totally a virtualenv
         base_path.ensure(bindir, fname)
         assert _in_venv(base_path) is True
 
     def test_custom_norecursedirs(self, testdir):
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
             norecursedirs = mydir xyz*
-        """)
+        """
+        )
         tmpdir = testdir.tmpdir
         tmpdir.ensure("mydir", "test_hello.py").write("def test_1(): pass")
         tmpdir.ensure("xyz123", "test_2.py").write("def test_2(): 0/0")
         tmpdir.ensure("xy", "test_ok.py").write("def test_3(): pass")
         rec = testdir.inline_run()
         rec.assertoutcome(passed=1)
         rec = testdir.inline_run("xyz123/test_2.py")
         rec.assertoutcome(failed=1)
 
     def test_testpaths_ini(self, testdir, monkeypatch):
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
             testpaths = gui uts
-        """)
+        """
+        )
         tmpdir = testdir.tmpdir
         tmpdir.ensure("env", "test_1.py").write("def test_env(): pass")
         tmpdir.ensure("gui", "test_2.py").write("def test_gui(): pass")
         tmpdir.ensure("uts", "test_3.py").write("def test_uts(): pass")
 
         # executing from rootdir only tests from `testpaths` directories
         # are collected
-        items, reprec = testdir.inline_genitems('-v')
-        assert [x.name for x in items] == ['test_gui', 'test_uts']
+        items, reprec = testdir.inline_genitems("-v")
+        assert [x.name for x in items] == ["test_gui", "test_uts"]
 
         # check that explicitly passing directories in the command-line
         # collects the tests
-        for dirname in ('env', 'gui', 'uts'):
+        for dirname in ("env", "gui", "uts"):
             items, reprec = testdir.inline_genitems(tmpdir.join(dirname))
-            assert [x.name for x in items] == ['test_%s' % dirname]
+            assert [x.name for x in items] == ["test_%s" % dirname]
 
         # changing cwd to each subdirectory and running pytest without
         # arguments collects the tests in that directory normally
-        for dirname in ('env', 'gui', 'uts'):
+        for dirname in ("env", "gui", "uts"):
             monkeypatch.chdir(testdir.tmpdir.join(dirname))
             items, reprec = testdir.inline_genitems()
-            assert [x.name for x in items] == ['test_%s' % dirname]
+            assert [x.name for x in items] == ["test_%s" % dirname]
 
 
 class TestCollectPluginHookRelay(object):
+
     def test_pytest_collect_file(self, testdir):
         wascalled = []
 
         class Plugin(object):
+
             def pytest_collect_file(self, path, parent):
                 if not path.basename.startswith("."):
                     # Ignore hidden files, e.g. .testmondata.
                     wascalled.append(path)
 
         testdir.makefile(".abc", "xyz")
         pytest.main([testdir.tmpdir], plugins=[Plugin()])
         assert len(wascalled) == 1
-        assert wascalled[0].ext == '.abc'
+        assert wascalled[0].ext == ".abc"
 
     def test_pytest_collect_directory(self, testdir):
         wascalled = []
 
         class Plugin(object):
+
             def pytest_collect_directory(self, path, parent):
                 wascalled.append(path.basename)
 
         testdir.mkdir("hello")
         testdir.mkdir("world")
         pytest.main(testdir.tmpdir, plugins=[Plugin()])
         assert "hello" in wascalled
         assert "world" in wascalled
 
 
 class TestPrunetraceback(object):
 
     def test_custom_repr_failure(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import not_exists
-        """)
-        testdir.makeconftest("""
+        """
+        )
+        testdir.makeconftest(
+            """
             import pytest
             def pytest_collect_file(path, parent):
                 return MyFile(path, parent)
             class MyError(Exception):
                 pass
             class MyFile(pytest.File):
                 def collect(self):
                     raise MyError()
                 def repr_failure(self, excinfo):
                     if excinfo.errisinstance(MyError):
                         return "hello world"
                     return pytest.File.repr_failure(self, excinfo)
-        """)
+        """
+        )
 
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            "*ERROR collecting*",
-            "*hello world*",
-        ])
+        result.stdout.fnmatch_lines(["*ERROR collecting*", "*hello world*"])
 
     @pytest.mark.xfail(reason="other mechanism for adding to reporting needed")
     def test_collect_report_postprocessing(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import not_exists
-        """)
-        testdir.makeconftest("""
+        """
+        )
+        testdir.makeconftest(
+            """
             import pytest
             @pytest.hookimpl(hookwrapper=True)
             def pytest_make_collect_report():
                 outcome = yield
                 rep = outcome.get_result()
                 rep.headerlines += ["header1"]
                 outcome.force_result(rep)
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            "*ERROR collecting*",
-            "*header1*",
-        ])
+        result.stdout.fnmatch_lines(["*ERROR collecting*", "*header1*"])
 
 
 class TestCustomConftests(object):
+
     def test_ignore_collect_path(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_ignore_collect(path, config):
                 return path.basename.startswith("x") or \
                        path.basename == "test_one.py"
-        """)
+        """
+        )
         sub = testdir.mkdir("xy123")
         sub.ensure("test_hello.py").write("syntax error")
         sub.join("conftest.py").write("syntax error")
         testdir.makepyfile("def test_hello(): pass")
         testdir.makepyfile(test_one="syntax error")
         result = testdir.runpytest("--fulltrace")
         assert result.ret == 0
         result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_ignore_collect_not_called_on_argument(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_ignore_collect(path, config):
                 return True
-        """)
+        """
+        )
         p = testdir.makepyfile("def test_hello(): pass")
         result = testdir.runpytest(p)
         assert result.ret == 0
         result.stdout.fnmatch_lines("*1 passed*")
         result = testdir.runpytest()
         assert result.ret == EXIT_NOTESTSCOLLECTED
         result.stdout.fnmatch_lines("*collected 0 items*")
 
     def test_collectignore_exclude_on_option(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             collect_ignore = ['hello', 'test_world.py']
             def pytest_addoption(parser):
                 parser.addoption("--XX", action="store_true", default=False)
             def pytest_configure(config):
                 if config.getvalue("XX"):
                     collect_ignore[:] = []
-        """)
+        """
+        )
         testdir.mkdir("hello")
         testdir.makepyfile(test_world="def test_hello(): pass")
         result = testdir.runpytest()
         assert result.ret == EXIT_NOTESTSCOLLECTED
         assert "passed" not in result.stdout.str()
         result = testdir.runpytest("--XX")
         assert result.ret == 0
         assert "passed" in result.stdout.str()
 
     def test_pytest_fs_collect_hooks_are_seen(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             class MyModule(pytest.Module):
                 pass
             def pytest_collect_file(path, parent):
                 if path.ext == ".py":
                     return MyModule(path, parent)
-        """)
+        """
+        )
         testdir.mkdir("sub")
         testdir.makepyfile("def test_x(): pass")
         result = testdir.runpytest("--collect-only")
-        result.stdout.fnmatch_lines([
-            "*MyModule*",
-            "*test_x*"
-        ])
+        result.stdout.fnmatch_lines(["*MyModule*", "*test_x*"])
 
     def test_pytest_collect_file_from_sister_dir(self, testdir):
         sub1 = testdir.mkpydir("sub1")
         sub2 = testdir.mkpydir("sub2")
-        conf1 = testdir.makeconftest("""
+        conf1 = testdir.makeconftest(
+            """
             import pytest
             class MyModule1(pytest.Module):
                 pass
             def pytest_collect_file(path, parent):
                 if path.ext == ".py":
                     return MyModule1(path, parent)
-        """)
+        """
+        )
         conf1.move(sub1.join(conf1.basename))
-        conf2 = testdir.makeconftest("""
+        conf2 = testdir.makeconftest(
+            """
             import pytest
             class MyModule2(pytest.Module):
                 pass
             def pytest_collect_file(path, parent):
                 if path.ext == ".py":
                     return MyModule2(path, parent)
-        """)
+        """
+        )
         conf2.move(sub2.join(conf2.basename))
         p = testdir.makepyfile("def test_x(): pass")
         p.copy(sub1.join(p.basename))
         p.copy(sub2.join(p.basename))
         result = testdir.runpytest("--collect-only")
-        result.stdout.fnmatch_lines([
-            "*MyModule1*",
-            "*MyModule2*",
-            "*test_x*"
-        ])
+        result.stdout.fnmatch_lines(["*MyModule1*", "*MyModule2*", "*test_x*"])
 
 
 class TestSession(object):
+
     def test_parsearg(self, testdir):
         p = testdir.makepyfile("def test_func(): pass")
         subdir = testdir.mkdir("sub")
         subdir.ensure("__init__.py")
         target = subdir.join(p.basename)
         p.move(target)
         subdir.chdir()
         config = testdir.parseconfig(p.basename)
@@ -419,254 +469,284 @@ class TestSession(object):
         # root2 = rcol.perform_collect([rcol.nodeid], genitems=False)[0]
         # assert root2 == rcol, rootid
         colitems = rcol.perform_collect([rcol.nodeid], genitems=False)
         assert len(colitems) == 1
         assert colitems[0].fspath == p
 
     def get_reported_items(self, hookrec):
         """Return pytest.Item instances reported by the pytest_collectreport hook"""
-        calls = hookrec.getcalls('pytest_collectreport')
-        return [x for call in calls for x in call.report.result
-                if isinstance(x, pytest.Item)]
+        calls = hookrec.getcalls("pytest_collectreport")
+        return [
+            x
+            for call in calls
+            for x in call.report.result
+            if isinstance(x, pytest.Item)
+        ]
 
     def test_collect_protocol_single_function(self, testdir):
         p = testdir.makepyfile("def test_func(): pass")
         id = "::".join([p.basename, "test_func"])
         items, hookrec = testdir.inline_genitems(id)
         item, = items
         assert item.name == "test_func"
         newid = item.nodeid
         assert newid == id
-        py.std.pprint.pprint(hookrec.calls)
+        pprint.pprint(hookrec.calls)
         topdir = testdir.tmpdir  # noqa
-        hookrec.assert_contains([
-            ("pytest_collectstart", "collector.fspath == topdir"),
-            ("pytest_make_collect_report", "collector.fspath == topdir"),
-            ("pytest_collectstart", "collector.fspath == p"),
-            ("pytest_make_collect_report", "collector.fspath == p"),
-            ("pytest_pycollect_makeitem", "name == 'test_func'"),
-            ("pytest_collectreport", "report.result[0].name == 'test_func'"),
-        ])
+        hookrec.assert_contains(
+            [
+                ("pytest_collectstart", "collector.fspath == topdir"),
+                ("pytest_make_collect_report", "collector.fspath == topdir"),
+                ("pytest_collectstart", "collector.fspath == p"),
+                ("pytest_make_collect_report", "collector.fspath == p"),
+                ("pytest_pycollect_makeitem", "name == 'test_func'"),
+                ("pytest_collectreport", "report.result[0].name == 'test_func'"),
+            ]
+        )
         # ensure we are reporting the collection of the single test item (#2464)
-        assert [x.name for x in self.get_reported_items(hookrec)] == ['test_func']
+        assert [x.name for x in self.get_reported_items(hookrec)] == ["test_func"]
 
     def test_collect_protocol_method(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             class TestClass(object):
                 def test_method(self):
                     pass
-        """)
+        """
+        )
         normid = p.basename + "::TestClass::()::test_method"
-        for id in [p.basename,
-                   p.basename + "::TestClass",
-                   p.basename + "::TestClass::()",
-                   normid,
-                   ]:
+        for id in [
+            p.basename,
+            p.basename + "::TestClass",
+            p.basename + "::TestClass::()",
+            normid,
+        ]:
             items, hookrec = testdir.inline_genitems(id)
             assert len(items) == 1
             assert items[0].name == "test_method"
             newid = items[0].nodeid
             assert newid == normid
             # ensure we are reporting the collection of the single test item (#2464)
-            assert [x.name for x in self.get_reported_items(hookrec)] == ['test_method']
+            assert [x.name for x in self.get_reported_items(hookrec)] == ["test_method"]
 
     def test_collect_custom_nodes_multi_id(self, testdir):
         p = testdir.makepyfile("def test_func(): pass")
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             class SpecialItem(pytest.Item):
                 def runtest(self):
                     return # ok
             class SpecialFile(pytest.File):
                 def collect(self):
                     return [SpecialItem(name="check", parent=self)]
             def pytest_collect_file(path, parent):
                 if path.basename == %r:
                     return SpecialFile(fspath=path, parent=parent)
-        """ % p.basename)
+        """
+            % p.basename
+        )
         id = p.basename
 
         items, hookrec = testdir.inline_genitems(id)
-        py.std.pprint.pprint(hookrec.calls)
+        pprint.pprint(hookrec.calls)
         assert len(items) == 2
-        hookrec.assert_contains([
-            ("pytest_collectstart",
-                "collector.fspath == collector.session.fspath"),
-            ("pytest_collectstart",
-                "collector.__class__.__name__ == 'SpecialFile'"),
-            ("pytest_collectstart",
-                "collector.__class__.__name__ == 'Module'"),
-            ("pytest_pycollect_makeitem", "name == 'test_func'"),
-            ("pytest_collectreport", "report.nodeid.startswith(p.basename)"),
-        ])
+        hookrec.assert_contains(
+            [
+                ("pytest_collectstart", "collector.fspath == collector.session.fspath"),
+                (
+                    "pytest_collectstart",
+                    "collector.__class__.__name__ == 'SpecialFile'",
+                ),
+                ("pytest_collectstart", "collector.__class__.__name__ == 'Module'"),
+                ("pytest_pycollect_makeitem", "name == 'test_func'"),
+                ("pytest_collectreport", "report.nodeid.startswith(p.basename)"),
+            ]
+        )
         assert len(self.get_reported_items(hookrec)) == 2
 
     def test_collect_subdir_event_ordering(self, testdir):
         p = testdir.makepyfile("def test_func(): pass")
         aaa = testdir.mkpydir("aaa")
         test_aaa = aaa.join("test_aaa.py")
         p.move(test_aaa)
 
         items, hookrec = testdir.inline_genitems()
         assert len(items) == 1
-        py.std.pprint.pprint(hookrec.calls)
-        hookrec.assert_contains([
-            ("pytest_collectstart", "collector.fspath == test_aaa"),
-            ("pytest_pycollect_makeitem", "name == 'test_func'"),
-            ("pytest_collectreport",
-             "report.nodeid.startswith('aaa/test_aaa.py')"),
-        ])
+        pprint.pprint(hookrec.calls)
+        hookrec.assert_contains(
+            [
+                ("pytest_collectstart", "collector.fspath == test_aaa"),
+                ("pytest_pycollect_makeitem", "name == 'test_func'"),
+                ("pytest_collectreport", "report.nodeid.startswith('aaa/test_aaa.py')"),
+            ]
+        )
 
     def test_collect_two_commandline_args(self, testdir):
         p = testdir.makepyfile("def test_func(): pass")
         aaa = testdir.mkpydir("aaa")
         bbb = testdir.mkpydir("bbb")
         test_aaa = aaa.join("test_aaa.py")
         p.copy(test_aaa)
         test_bbb = bbb.join("test_bbb.py")
         p.move(test_bbb)
 
         id = "."
 
         items, hookrec = testdir.inline_genitems(id)
         assert len(items) == 2
-        py.std.pprint.pprint(hookrec.calls)
-        hookrec.assert_contains([
-            ("pytest_collectstart", "collector.fspath == test_aaa"),
-            ("pytest_pycollect_makeitem", "name == 'test_func'"),
-            ("pytest_collectreport", "report.nodeid == 'aaa/test_aaa.py'"),
-            ("pytest_collectstart", "collector.fspath == test_bbb"),
-            ("pytest_pycollect_makeitem", "name == 'test_func'"),
-            ("pytest_collectreport", "report.nodeid == 'bbb/test_bbb.py'"),
-        ])
+        pprint.pprint(hookrec.calls)
+        hookrec.assert_contains(
+            [
+                ("pytest_collectstart", "collector.fspath == test_aaa"),
+                ("pytest_pycollect_makeitem", "name == 'test_func'"),
+                ("pytest_collectreport", "report.nodeid == 'aaa/test_aaa.py'"),
+                ("pytest_collectstart", "collector.fspath == test_bbb"),
+                ("pytest_pycollect_makeitem", "name == 'test_func'"),
+                ("pytest_collectreport", "report.nodeid == 'bbb/test_bbb.py'"),
+            ]
+        )
 
     def test_serialization_byid(self, testdir):
         testdir.makepyfile("def test_func(): pass")
         items, hookrec = testdir.inline_genitems()
         assert len(items) == 1
         item, = items
         items2, hookrec = testdir.inline_genitems(item.nodeid)
         item2, = items2
         assert item2.name == item.name
         assert item2.fspath == item.fspath
 
     def test_find_byid_without_instance_parents(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             class TestClass(object):
                 def test_method(self):
                     pass
-        """)
+        """
+        )
         arg = p.basename + "::TestClass::test_method"
         items, hookrec = testdir.inline_genitems(arg)
         assert len(items) == 1
         item, = items
         assert item.nodeid.endswith("TestClass::()::test_method")
         # ensure we are reporting the collection of the single test item (#2464)
-        assert [x.name for x in self.get_reported_items(hookrec)] == ['test_method']
+        assert [x.name for x in self.get_reported_items(hookrec)] == ["test_method"]
 
 
 class Test_getinitialnodes(object):
+
     def test_global_file(self, testdir, tmpdir):
         x = tmpdir.ensure("x.py")
         with tmpdir.as_cwd():
             config = testdir.parseconfigure(x)
         col = testdir.getnode(config, x)
         assert isinstance(col, pytest.Module)
-        assert col.name == 'x.py'
+        assert col.name == "x.py"
         assert col.parent.parent is None
         for col in col.listchain():
             assert col.config is config
 
     def test_pkgfile(self, testdir):
         tmpdir = testdir.tmpdir
         subdir = tmpdir.join("subdir")
         x = subdir.ensure("x.py")
         subdir.ensure("__init__.py")
         with subdir.as_cwd():
             config = testdir.parseconfigure(x)
         col = testdir.getnode(config, x)
         assert isinstance(col, pytest.Module)
-        assert col.name == 'x.py'
+        assert col.name == "x.py"
         assert col.parent.parent is None
         for col in col.listchain():
             assert col.config is config
 
 
 class Test_genitems(object):
+
     def test_check_collect_hashes(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_1():
                 pass
 
             def test_2():
                 pass
-        """)
+        """
+        )
         p.copy(p.dirpath(p.purebasename + "2" + ".py"))
         items, reprec = testdir.inline_genitems(p.dirpath())
         assert len(items) == 4
         for numi, i in enumerate(items):
             for numj, j in enumerate(items):
                 if numj != numi:
                     assert hash(i) != hash(j)
                     assert i != j
 
     def test_example_items1(self, testdir):
-        p = testdir.makepyfile('''
+        p = testdir.makepyfile(
+            """
             def testone():
                 pass
 
             class TestX(object):
                 def testmethod_one(self):
                     pass
 
             class TestY(TestX):
                 pass
-        ''')
+        """
+        )
         items, reprec = testdir.inline_genitems(p)
         assert len(items) == 3
-        assert items[0].name == 'testone'
-        assert items[1].name == 'testmethod_one'
-        assert items[2].name == 'testmethod_one'
+        assert items[0].name == "testone"
+        assert items[1].name == "testmethod_one"
+        assert items[2].name == "testmethod_one"
 
         # let's also test getmodpath here
         assert items[0].getmodpath() == "testone"
         assert items[1].getmodpath() == "TestX.testmethod_one"
         assert items[2].getmodpath() == "TestY.testmethod_one"
 
         s = items[0].getmodpath(stopatmodule=False)
         assert s.endswith("test_example_items1.testone")
         print(s)
 
     def test_class_and_functions_discovery_using_glob(self, testdir):
         """
         tests that python_classes and python_functions config options work
         as prefixes and glob-like patterns (issue #600).
         """
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
             python_classes = *Suite Test
             python_functions = *_test test
-        """)
-        p = testdir.makepyfile('''
+        """
+        )
+        p = testdir.makepyfile(
+            """
             class MyTestSuite(object):
                 def x_test(self):
                     pass
 
             class TestCase(object):
                 def test_y(self):
                     pass
-        ''')
+        """
+        )
         items, reprec = testdir.inline_genitems(p)
         ids = [x.getmodpath() for x in items]
-        assert ids == ['MyTestSuite.x_test', 'TestCase.test_y']
+        assert ids == ["MyTestSuite.x_test", "TestCase.test_y"]
 
 
 def test_matchnodes_two_collections_same_file(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         import pytest
         def pytest_configure(config):
             config.pluginmanager.register(Plugin2())
 
         class Plugin2(object):
             def pytest_collect_file(self, path, parent):
                 if path.ext == ".abc":
                     return MyFile2(path, parent)
@@ -680,49 +760,51 @@ def test_matchnodes_two_collections_same
                 pass
         class MyFile2(pytest.File):
             def collect(self):
                 return [Item2("hello", parent=self)]
 
         class Item2(pytest.Item):
             def runtest(self):
                 pass
-    """)
+    """
+    )
     p = testdir.makefile(".abc", "")
     result = testdir.runpytest()
     assert result.ret == 0
-    result.stdout.fnmatch_lines([
-        "*2 passed*",
-    ])
+    result.stdout.fnmatch_lines(["*2 passed*"])
     res = testdir.runpytest("%s::hello" % p.basename)
-    res.stdout.fnmatch_lines([
-        "*1 passed*",
-    ])
+    res.stdout.fnmatch_lines(["*1 passed*"])
 
 
 class TestNodekeywords(object):
+
     def test_no_under(self, testdir):
-        modcol = testdir.getmodulecol("""
+        modcol = testdir.getmodulecol(
+            """
             def test_pass(): pass
             def test_fail(): assert 0
-        """)
+        """
+        )
         values = list(modcol.keywords)
         assert modcol.name in values
         for x in values:
             assert not x.startswith("_")
         assert modcol.name in repr(modcol.keywords)
 
     def test_issue345(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_should_not_be_selected():
                 assert False, 'I should not have been selected to run'
 
             def test___repr__():
                 pass
-        """)
+        """
+        )
         reprec = testdir.inline_run("-k repr")
         reprec.assertoutcome(passed=1, failed=0)
 
 
 COLLECTION_ERROR_PY_FILES = dict(
     test_01_failure="""
         def test_1():
             assert False
@@ -746,112 +828,117 @@ COLLECTION_ERROR_PY_FILES = dict(
 
 def test_exit_on_collection_error(testdir):
     """Verify that all collection errors are collected and no tests executed"""
     testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)
 
     res = testdir.runpytest()
     assert res.ret == 2
 
-    res.stdout.fnmatch_lines([
-        "collected 2 items / 2 errors",
-        "*ERROR collecting test_02_import_error.py*",
-        "*No module named *asdfa*",
-        "*ERROR collecting test_03_import_error.py*",
-        "*No module named *asdfa*",
-    ])
+    res.stdout.fnmatch_lines(
+        [
+            "collected 2 items / 2 errors",
+            "*ERROR collecting test_02_import_error.py*",
+            "*No module named *asdfa*",
+            "*ERROR collecting test_03_import_error.py*",
+            "*No module named *asdfa*",
+        ]
+    )
 
 
 def test_exit_on_collection_with_maxfail_smaller_than_n_errors(testdir):
     """
     Verify collection is aborted once maxfail errors are encountered ignoring
     further modules which would cause more collection errors.
     """
     testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)
 
     res = testdir.runpytest("--maxfail=1")
     assert res.ret == 1
 
-    res.stdout.fnmatch_lines([
-        "*ERROR collecting test_02_import_error.py*",
-        "*No module named *asdfa*",
-    ])
+    res.stdout.fnmatch_lines(
+        ["*ERROR collecting test_02_import_error.py*", "*No module named *asdfa*"]
+    )
 
-    assert 'test_03' not in res.stdout.str()
+    assert "test_03" not in res.stdout.str()
 
 
 def test_exit_on_collection_with_maxfail_bigger_than_n_errors(testdir):
     """
     Verify the test run aborts due to collection errors even if maxfail count of
     errors was not reached.
     """
     testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)
 
     res = testdir.runpytest("--maxfail=4")
     assert res.ret == 2
 
-    res.stdout.fnmatch_lines([
-        "collected 2 items / 2 errors",
-        "*ERROR collecting test_02_import_error.py*",
-        "*No module named *asdfa*",
-        "*ERROR collecting test_03_import_error.py*",
-        "*No module named *asdfa*",
-    ])
+    res.stdout.fnmatch_lines(
+        [
+            "collected 2 items / 2 errors",
+            "*ERROR collecting test_02_import_error.py*",
+            "*No module named *asdfa*",
+            "*ERROR collecting test_03_import_error.py*",
+            "*No module named *asdfa*",
+        ]
+    )
 
 
 def test_continue_on_collection_errors(testdir):
     """
     Verify tests are executed even when collection errors occur when the
     --continue-on-collection-errors flag is set
     """
     testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)
 
     res = testdir.runpytest("--continue-on-collection-errors")
     assert res.ret == 1
 
-    res.stdout.fnmatch_lines([
-        "collected 2 items / 2 errors",
-        "*1 failed, 1 passed, 2 error*",
-    ])
+    res.stdout.fnmatch_lines(
+        ["collected 2 items / 2 errors", "*1 failed, 1 passed, 2 error*"]
+    )
 
 
 def test_continue_on_collection_errors_maxfail(testdir):
     """
     Verify tests are executed even when collection errors occur and that maxfail
     is honoured (including the collection error count).
     4 tests: 2 collection errors + 1 failure + 1 success
     test_4 is never executed because the test run is with --maxfail=3 which
     means it is interrupted after the 2 collection errors + 1 failure.
     """
     testdir.makepyfile(**COLLECTION_ERROR_PY_FILES)
 
     res = testdir.runpytest("--continue-on-collection-errors", "--maxfail=3")
     assert res.ret == 1
 
-    res.stdout.fnmatch_lines([
-        "collected 2 items / 2 errors",
-        "*1 failed, 2 error*",
-    ])
+    res.stdout.fnmatch_lines(["collected 2 items / 2 errors", "*1 failed, 2 error*"])
 
 
 def test_fixture_scope_sibling_conftests(testdir):
     """Regression test case for https://github.com/pytest-dev/pytest/issues/2836"""
     foo_path = testdir.mkpydir("foo")
-    foo_path.join("conftest.py").write(_pytest._code.Source("""
+    foo_path.join("conftest.py").write(
+        _pytest._code.Source(
+            """
         import pytest
         @pytest.fixture
         def fix():
             return 1
-    """))
+    """
+        )
+    )
     foo_path.join("test_foo.py").write("def test_foo(fix): assert fix == 1")
 
     # Tests in `food/` should not see the conftest fixture from `foo/`
     food_path = testdir.mkpydir("food")
     food_path.join("test_food.py").write("def test_food(fix): assert fix == 1")
 
     res = testdir.runpytest()
     assert res.ret == 1
 
-    res.stdout.fnmatch_lines([
-        "*ERROR at setup of test_food*",
-        "E*fixture 'fix' not found",
-        "*1 passed, 1 error*",
-    ])
+    res.stdout.fnmatch_lines(
+        [
+            "*ERROR at setup of test_food*",
+            "E*fixture 'fix' not found",
+            "*1 passed, 1 error*",
+        ]
+    )
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_compat.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_compat.py
@@ -2,100 +2,109 @@ from __future__ import absolute_import, 
 import sys
 
 import pytest
 from _pytest.compat import is_generator, get_real_func, safe_getattr
 from _pytest.outcomes import OutcomeException
 
 
 def test_is_generator():
+
     def zap():
         yield
 
     def foo():
         pass
 
     assert is_generator(zap)
     assert not is_generator(foo)
 
 
 def test_real_func_loop_limit():
 
     class Evil(object):
+
         def __init__(self):
             self.left = 1000
 
         def __repr__(self):
             return "<Evil left={left}>".format(left=self.left)
 
         def __getattr__(self, attr):
             if not self.left:
-                raise RuntimeError('its over')
+                raise RuntimeError("its over")
             self.left -= 1
             return self
 
     evil = Evil()
 
     with pytest.raises(ValueError):
         res = get_real_func(evil)
         print(res)
 
 
-@pytest.mark.skipif(sys.version_info < (3, 4),
-                    reason='asyncio available in Python 3.4+')
+@pytest.mark.skipif(
+    sys.version_info < (3, 4), reason="asyncio available in Python 3.4+"
+)
 def test_is_generator_asyncio(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         from _pytest.compat import is_generator
         import asyncio
         @asyncio.coroutine
         def baz():
             yield from [1,2,3]
 
         def test_is_generator_asyncio():
             assert not is_generator(baz)
-    """)
+    """
+    )
     # avoid importing asyncio into pytest's own process,
     # which in turn imports logging (#8)
     result = testdir.runpytest_subprocess()
-    result.stdout.fnmatch_lines(['*1 passed*'])
+    result.stdout.fnmatch_lines(["*1 passed*"])
 
 
-@pytest.mark.skipif(sys.version_info < (3, 5),
-                    reason='async syntax available in Python 3.5+')
+@pytest.mark.skipif(
+    sys.version_info < (3, 5), reason="async syntax available in Python 3.5+"
+)
 def test_is_generator_async_syntax(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         from _pytest.compat import is_generator
         def test_is_generator_py35():
             async def foo():
                 await foo()
 
             async def bar():
                 pass
 
             assert not is_generator(foo)
             assert not is_generator(bar)
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines(['*1 passed*'])
+    result.stdout.fnmatch_lines(["*1 passed*"])
 
 
 class ErrorsHelper(object):
+
     @property
     def raise_exception(self):
-        raise Exception('exception should be catched')
+        raise Exception("exception should be catched")
 
     @property
     def raise_fail(self):
-        pytest.fail('fail should be catched')
+        pytest.fail("fail should be catched")
 
 
 def test_helper_failures():
     helper = ErrorsHelper()
     with pytest.raises(Exception):
         helper.raise_exception
     with pytest.raises(OutcomeException):
         helper.raise_fail
 
 
 def test_safe_getattr():
     helper = ErrorsHelper()
-    assert safe_getattr(helper, 'raise_exception', 'default') == 'default'
-    assert safe_getattr(helper, 'raise_fail', 'default') == 'default'
+    assert safe_getattr(helper, "raise_exception", "default") == "default"
+    assert safe_getattr(helper, "raise_fail", "default") == "default"
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_config.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_config.py
@@ -1,691 +1,825 @@
 from __future__ import absolute_import, division, print_function
 import sys
-import py
+import textwrap
 import pytest
 
 import _pytest._code
-from _pytest.config import getcfg, get_common_ancestor, determine_setup, _iter_rewritable_modules
+from _pytest.config.findpaths import getcfg, get_common_ancestor, determine_setup
+from _pytest.config import _iter_rewritable_modules
 from _pytest.main import EXIT_NOTESTSCOLLECTED
 
 
 class TestParseIni(object):
 
-    @pytest.mark.parametrize('section, filename',
-                             [('pytest', 'pytest.ini'), ('tool:pytest', 'setup.cfg')])
+    @pytest.mark.parametrize(
+        "section, filename", [("pytest", "pytest.ini"), ("tool:pytest", "setup.cfg")]
+    )
     def test_getcfg_and_config(self, testdir, tmpdir, section, filename):
         sub = tmpdir.mkdir("sub")
         sub.chdir()
-        tmpdir.join(filename).write(_pytest._code.Source("""
+        tmpdir.join(filename).write(
+            _pytest._code.Source(
+                """
             [{section}]
             name = value
-        """.format(section=section)))
+        """.format(
+                    section=section
+                )
+            )
+        )
         rootdir, inifile, cfg = getcfg([sub])
-        assert cfg['name'] == "value"
+        assert cfg["name"] == "value"
         config = testdir.parseconfigure(sub)
-        assert config.inicfg['name'] == 'value'
+        assert config.inicfg["name"] == "value"
 
     def test_getcfg_empty_path(self):
         """correctly handle zero length arguments (a la pytest '')"""
-        getcfg([''])
+        getcfg([""])
 
     def test_append_parse_args(self, testdir, tmpdir, monkeypatch):
-        monkeypatch.setenv('PYTEST_ADDOPTS', '--color no -rs --tb="short"')
-        tmpdir.join("pytest.ini").write(_pytest._code.Source("""
+        monkeypatch.setenv("PYTEST_ADDOPTS", '--color no -rs --tb="short"')
+        tmpdir.join("pytest.ini").write(
+            _pytest._code.Source(
+                """
             [pytest]
             addopts = --verbose
-        """))
+        """
+            )
+        )
         config = testdir.parseconfig(tmpdir)
-        assert config.option.color == 'no'
-        assert config.option.reportchars == 's'
-        assert config.option.tbstyle == 'short'
+        assert config.option.color == "no"
+        assert config.option.reportchars == "s"
+        assert config.option.tbstyle == "short"
         assert config.option.verbose
 
     def test_tox_ini_wrong_version(self, testdir):
-        testdir.makefile('.ini', tox="""
+        testdir.makefile(
+            ".ini",
+            tox="""
             [pytest]
             minversion=9.0
-        """)
+        """,
+        )
         result = testdir.runpytest()
         assert result.ret != 0
-        result.stderr.fnmatch_lines([
-            "*tox.ini:2*requires*9.0*actual*"
-        ])
+        result.stderr.fnmatch_lines(["*tox.ini:2*requires*9.0*actual*"])
 
-    @pytest.mark.parametrize("section, name", [
-        ('tool:pytest', 'setup.cfg'),
-        ('pytest', 'tox.ini'),
-        ('pytest', 'pytest.ini')],
+    @pytest.mark.parametrize(
+        "section, name",
+        [("tool:pytest", "setup.cfg"), ("pytest", "tox.ini"), ("pytest", "pytest.ini")],
     )
     def test_ini_names(self, testdir, name, section):
-        testdir.tmpdir.join(name).write(py.std.textwrap.dedent("""
+        testdir.tmpdir.join(name).write(
+            textwrap.dedent(
+                """
             [{section}]
             minversion = 1.0
-        """.format(section=section)))
+        """.format(
+                    section=section
+                )
+            )
+        )
         config = testdir.parseconfig()
         assert config.getini("minversion") == "1.0"
 
     def test_toxini_before_lower_pytestini(self, testdir):
         sub = testdir.tmpdir.mkdir("sub")
-        sub.join("tox.ini").write(py.std.textwrap.dedent("""
+        sub.join("tox.ini").write(
+            textwrap.dedent(
+                """
             [pytest]
             minversion = 2.0
-        """))
-        testdir.tmpdir.join("pytest.ini").write(py.std.textwrap.dedent("""
+        """
+            )
+        )
+        testdir.tmpdir.join("pytest.ini").write(
+            textwrap.dedent(
+                """
             [pytest]
             minversion = 1.5
-        """))
+        """
+            )
+        )
         config = testdir.parseconfigure(sub)
         assert config.getini("minversion") == "2.0"
 
     @pytest.mark.xfail(reason="probably not needed")
     def test_confcutdir(self, testdir):
         sub = testdir.mkdir("sub")
         sub.chdir()
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
             addopts = --qwe
-        """)
+        """
+        )
         result = testdir.inline_run("--confcutdir=.")
         assert result.ret == 0
 
 
 class TestConfigCmdlineParsing(object):
+
     def test_parsing_again_fails(self, testdir):
         config = testdir.parseconfig()
         pytest.raises(AssertionError, lambda: config.parse([]))
 
     def test_explicitly_specified_config_file_is_loaded(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_addoption(parser):
                 parser.addini("custom", "")
-        """)
-        testdir.makeini("""
+        """
+        )
+        testdir.makeini(
+            """
             [pytest]
             custom = 0
-        """)
-        testdir.makefile(".cfg", custom="""
+        """
+        )
+        testdir.makefile(
+            ".cfg",
+            custom="""
             [pytest]
             custom = 1
-        """)
+        """,
+        )
         config = testdir.parseconfig("-c", "custom.cfg")
         assert config.getini("custom") == "1"
 
+        testdir.makefile(
+            ".cfg",
+            custom_tool_pytest_section="""
+            [tool:pytest]
+            custom = 1
+        """,
+        )
+        config = testdir.parseconfig("-c", "custom_tool_pytest_section.cfg")
+        assert config.getini("custom") == "1"
+
     def test_absolute_win32_path(self, testdir):
-        temp_cfg_file = testdir.makefile(".cfg", custom="""
+        temp_cfg_file = testdir.makefile(
+            ".cfg",
+            custom="""
             [pytest]
             addopts = --version
-        """)
+        """,
+        )
         from os.path import normpath
+
         temp_cfg_file = normpath(str(temp_cfg_file))
         ret = pytest.main("-c " + temp_cfg_file)
         assert ret == _pytest.main.EXIT_OK
 
 
 class TestConfigAPI(object):
+
     def test_config_trace(self, testdir):
         config = testdir.parseconfig()
         values = []
         config.trace.root.setwriter(values.append)
         config.trace("hello")
         assert len(values) == 1
         assert values[0] == "hello [config]\n"
 
     def test_config_getoption(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_addoption(parser):
                 parser.addoption("--hello", "-X", dest="hello")
-        """)
+        """
+        )
         config = testdir.parseconfig("--hello=this")
         for x in ("hello", "--hello", "-X"):
             assert config.getoption(x) == "this"
         pytest.raises(ValueError, "config.getoption('qweqwe')")
 
-    @pytest.mark.skipif('sys.version_info[0] < 3')
+    @pytest.mark.skipif("sys.version_info[0] < 3")
     def test_config_getoption_unicode(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             from __future__ import unicode_literals
 
             def pytest_addoption(parser):
                 parser.addoption('--hello', type=str)
-        """)
-        config = testdir.parseconfig('--hello=this')
-        assert config.getoption('hello') == 'this'
+        """
+        )
+        config = testdir.parseconfig("--hello=this")
+        assert config.getoption("hello") == "this"
 
     def test_config_getvalueorskip(self, testdir):
         config = testdir.parseconfig()
-        pytest.raises(pytest.skip.Exception,
-                      "config.getvalueorskip('hello')")
+        pytest.raises(pytest.skip.Exception, "config.getvalueorskip('hello')")
         verbose = config.getvalueorskip("verbose")
         assert verbose == config.option.verbose
 
     def test_config_getvalueorskip_None(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_addoption(parser):
                 parser.addoption("--hello")
-        """)
+        """
+        )
         config = testdir.parseconfig()
         with pytest.raises(pytest.skip.Exception):
-            config.getvalueorskip('hello')
+            config.getvalueorskip("hello")
 
     def test_getoption(self, testdir):
         config = testdir.parseconfig()
         with pytest.raises(ValueError):
-            config.getvalue('x')
+            config.getvalue("x")
         assert config.getoption("x", 1) == 1
 
     def test_getconftest_pathlist(self, testdir, tmpdir):
         somepath = tmpdir.join("x", "y", "z")
         p = tmpdir.join("conftest.py")
         p.write("pathlist = ['.', %r]" % str(somepath))
         config = testdir.parseconfigure(p)
-        assert config._getconftest_pathlist('notexist', path=tmpdir) is None
-        pl = config._getconftest_pathlist('pathlist', path=tmpdir)
+        assert config._getconftest_pathlist("notexist", path=tmpdir) is None
+        pl = config._getconftest_pathlist("pathlist", path=tmpdir)
         print(pl)
         assert len(pl) == 2
         assert pl[0] == tmpdir
         assert pl[1] == somepath
 
     def test_addini(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_addoption(parser):
                 parser.addini("myname", "my new ini value")
-        """)
-        testdir.makeini("""
+        """
+        )
+        testdir.makeini(
+            """
             [pytest]
             myname=hello
-        """)
+        """
+        )
         config = testdir.parseconfig()
         val = config.getini("myname")
         assert val == "hello"
-        pytest.raises(ValueError, config.getini, 'other')
+        pytest.raises(ValueError, config.getini, "other")
 
     def test_addini_pathlist(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_addoption(parser):
                 parser.addini("paths", "my new ini value", type="pathlist")
                 parser.addini("abc", "abc value")
-        """)
-        p = testdir.makeini("""
+        """
+        )
+        p = testdir.makeini(
+            """
             [pytest]
             paths=hello world/sub.py
-        """)
+        """
+        )
         config = testdir.parseconfig()
         values = config.getini("paths")
         assert len(values) == 2
-        assert values[0] == p.dirpath('hello')
-        assert values[1] == p.dirpath('world/sub.py')
-        pytest.raises(ValueError, config.getini, 'other')
+        assert values[0] == p.dirpath("hello")
+        assert values[1] == p.dirpath("world/sub.py")
+        pytest.raises(ValueError, config.getini, "other")
 
     def test_addini_args(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_addoption(parser):
                 parser.addini("args", "new args", type="args")
                 parser.addini("a2", "", "args", default="1 2 3".split())
-        """)
-        testdir.makeini("""
+        """
+        )
+        testdir.makeini(
+            """
             [pytest]
             args=123 "123 hello" "this"
-        """)
+        """
+        )
         config = testdir.parseconfig()
         values = config.getini("args")
         assert len(values) == 3
         assert values == ["123", "123 hello", "this"]
         values = config.getini("a2")
         assert values == list("123")
 
     def test_addini_linelist(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_addoption(parser):
                 parser.addini("xy", "", type="linelist")
                 parser.addini("a2", "", "linelist")
-        """)
-        testdir.makeini("""
+        """
+        )
+        testdir.makeini(
+            """
             [pytest]
             xy= 123 345
                 second line
-        """)
+        """
+        )
         config = testdir.parseconfig()
         values = config.getini("xy")
         assert len(values) == 2
         assert values == ["123 345", "second line"]
         values = config.getini("a2")
         assert values == []
 
-    @pytest.mark.parametrize('str_val, bool_val',
-                             [('True', True), ('no', False), ('no-ini', True)])
+    @pytest.mark.parametrize(
+        "str_val, bool_val", [("True", True), ("no", False), ("no-ini", True)]
+    )
     def test_addini_bool(self, testdir, str_val, bool_val):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_addoption(parser):
                 parser.addini("strip", "", type="bool", default=True)
-        """)
-        if str_val != 'no-ini':
-            testdir.makeini("""
+        """
+        )
+        if str_val != "no-ini":
+            testdir.makeini(
+                """
                 [pytest]
                 strip=%s
-            """ % str_val)
+            """
+                % str_val
+            )
         config = testdir.parseconfig()
         assert config.getini("strip") is bool_val
 
     def test_addinivalue_line_existing(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_addoption(parser):
                 parser.addini("xy", "", type="linelist")
-        """)
-        testdir.makeini("""
+        """
+        )
+        testdir.makeini(
+            """
             [pytest]
             xy= 123
-        """)
+        """
+        )
         config = testdir.parseconfig()
         values = config.getini("xy")
         assert len(values) == 1
         assert values == ["123"]
         config.addinivalue_line("xy", "456")
         values = config.getini("xy")
         assert len(values) == 2
         assert values == ["123", "456"]
 
     def test_addinivalue_line_new(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_addoption(parser):
                 parser.addini("xy", "", type="linelist")
-        """)
+        """
+        )
         config = testdir.parseconfig()
         assert not config.getini("xy")
         config.addinivalue_line("xy", "456")
         values = config.getini("xy")
         assert len(values) == 1
         assert values == ["456"]
         config.addinivalue_line("xy", "123")
         values = config.getini("xy")
         assert len(values) == 2
         assert values == ["456", "123"]
 
     def test_confcutdir_check_isdir(self, testdir):
         """Give an error if --confcutdir is not a valid directory (#2078)"""
         with pytest.raises(pytest.UsageError):
-            testdir.parseconfig('--confcutdir', testdir.tmpdir.join('file').ensure(file=1))
+            testdir.parseconfig(
+                "--confcutdir", testdir.tmpdir.join("file").ensure(file=1)
+            )
         with pytest.raises(pytest.UsageError):
-            testdir.parseconfig('--confcutdir', testdir.tmpdir.join('inexistant'))
-        config = testdir.parseconfig('--confcutdir', testdir.tmpdir.join('dir').ensure(dir=1))
-        assert config.getoption('confcutdir') == str(testdir.tmpdir.join('dir'))
+            testdir.parseconfig("--confcutdir", testdir.tmpdir.join("inexistant"))
+        config = testdir.parseconfig(
+            "--confcutdir", testdir.tmpdir.join("dir").ensure(dir=1)
+        )
+        assert config.getoption("confcutdir") == str(testdir.tmpdir.join("dir"))
 
-    @pytest.mark.parametrize('names, expected', [
-        (['bar.py'], ['bar']),
-        (['foo', 'bar.py'], []),
-        (['foo', 'bar.pyc'], []),
-        (['foo', '__init__.py'], ['foo']),
-        (['foo', 'bar', '__init__.py'], []),
-    ])
+    @pytest.mark.parametrize(
+        "names, expected",
+        [
+            (["bar.py"], ["bar"]),
+            (["foo", "bar.py"], []),
+            (["foo", "bar.pyc"], []),
+            (["foo", "__init__.py"], ["foo"]),
+            (["foo", "bar", "__init__.py"], []),
+        ],
+    )
     def test_iter_rewritable_modules(self, names, expected):
-        assert list(_iter_rewritable_modules(['/'.join(names)])) == expected
+        assert list(_iter_rewritable_modules(["/".join(names)])) == expected
 
 
 class TestConfigFromdictargs(object):
+
     def test_basic_behavior(self):
         from _pytest.config import Config
-        option_dict = {
-            'verbose': 444,
-            'foo': 'bar',
-            'capture': 'no',
-        }
-        args = ['a', 'b']
+
+        option_dict = {"verbose": 444, "foo": "bar", "capture": "no"}
+        args = ["a", "b"]
 
         config = Config.fromdictargs(option_dict, args)
         with pytest.raises(AssertionError):
-            config.parse(['should refuse to parse again'])
+            config.parse(["should refuse to parse again"])
         assert config.option.verbose == 444
-        assert config.option.foo == 'bar'
-        assert config.option.capture == 'no'
+        assert config.option.foo == "bar"
+        assert config.option.capture == "no"
         assert config.args == args
 
     def test_origargs(self):
         """Show that fromdictargs can handle args in their "orig" format"""
         from _pytest.config import Config
+
         option_dict = {}
-        args = ['-vvvv', '-s', 'a', 'b']
+        args = ["-vvvv", "-s", "a", "b"]
 
         config = Config.fromdictargs(option_dict, args)
-        assert config.args == ['a', 'b']
+        assert config.args == ["a", "b"]
         assert config._origargs == args
         assert config.option.verbose == 4
-        assert config.option.capture == 'no'
+        assert config.option.capture == "no"
 
     def test_inifilename(self, tmpdir):
-        tmpdir.join("foo/bar.ini").ensure().write(_pytest._code.Source("""
+        tmpdir.join("foo/bar.ini").ensure().write(
+            _pytest._code.Source(
+                """
             [pytest]
             name = value
-        """))
+        """
+            )
+        )
 
         from _pytest.config import Config
-        inifile = '../../foo/bar.ini'
-        option_dict = {
-            'inifilename': inifile,
-            'capture': 'no',
-        }
+
+        inifile = "../../foo/bar.ini"
+        option_dict = {"inifilename": inifile, "capture": "no"}
 
-        cwd = tmpdir.join('a/b')
-        cwd.join('pytest.ini').ensure().write(_pytest._code.Source("""
+        cwd = tmpdir.join("a/b")
+        cwd.join("pytest.ini").ensure().write(
+            _pytest._code.Source(
+                """
             [pytest]
             name = wrong-value
             should_not_be_set = true
-        """))
+        """
+            )
+        )
         with cwd.ensure(dir=True).as_cwd():
             config = Config.fromdictargs(option_dict, ())
 
         assert config.args == [str(cwd)]
         assert config.option.inifilename == inifile
-        assert config.option.capture == 'no'
+        assert config.option.capture == "no"
 
         # this indicates this is the file used for getting configuration values
         assert config.inifile == inifile
-        assert config.inicfg.get('name') == 'value'
-        assert config.inicfg.get('should_not_be_set') is None
+        assert config.inicfg.get("name") == "value"
+        assert config.inicfg.get("should_not_be_set") is None
 
 
 def test_options_on_small_file_do_not_blow_up(testdir):
+
     def runfiletest(opts):
         reprec = testdir.inline_run(*opts)
         passed, skipped, failed = reprec.countoutcomes()
         assert failed == 2
         assert skipped == passed == 0
-    path = testdir.makepyfile("""
+
+    path = testdir.makepyfile(
+        """
         def test_f1(): assert 0
         def test_f2(): assert 0
-    """)
+    """
+    )
 
-    for opts in ([], ['-l'], ['-s'], ['--tb=no'], ['--tb=short'],
-                 ['--tb=long'], ['--fulltrace'],
-                 ['--traceconfig'], ['-v'], ['-v', '-v']):
+    for opts in (
+        [],
+        ["-l"],
+        ["-s"],
+        ["--tb=no"],
+        ["--tb=short"],
+        ["--tb=long"],
+        ["--fulltrace"],
+        ["--traceconfig"],
+        ["-v"],
+        ["-v", "-v"],
+    ):
         runfiletest(opts + [path])
 
 
 def test_preparse_ordering_with_setuptools(testdir, monkeypatch):
     pkg_resources = pytest.importorskip("pkg_resources")
 
     def my_iter(name):
         assert name == "pytest11"
 
         class Dist(object):
-            project_name = 'spam'
-            version = '1.0'
+            project_name = "spam"
+            version = "1.0"
 
             def _get_metadata(self, name):
-                return ['foo.txt,sha256=abc,123']
+                return ["foo.txt,sha256=abc,123"]
 
         class EntryPoint(object):
             name = "mytestplugin"
             dist = Dist()
 
             def load(self):
+
                 class PseudoPlugin(object):
                     x = 42
+
                 return PseudoPlugin()
 
         return iter([EntryPoint()])
 
-    monkeypatch.setattr(pkg_resources, 'iter_entry_points', my_iter)
-    testdir.makeconftest("""
+    monkeypatch.setattr(pkg_resources, "iter_entry_points", my_iter)
+    testdir.makeconftest(
+        """
         pytest_plugins = "mytestplugin",
-    """)
+    """
+    )
     monkeypatch.setenv("PYTEST_PLUGINS", "mytestplugin")
     config = testdir.parseconfig()
     plugin = config.pluginmanager.getplugin("mytestplugin")
     assert plugin.x == 42
 
 
 def test_setuptools_importerror_issue1479(testdir, monkeypatch):
     pkg_resources = pytest.importorskip("pkg_resources")
 
     def my_iter(name):
         assert name == "pytest11"
 
         class Dist(object):
-            project_name = 'spam'
-            version = '1.0'
+            project_name = "spam"
+            version = "1.0"
 
             def _get_metadata(self, name):
-                return ['foo.txt,sha256=abc,123']
+                return ["foo.txt,sha256=abc,123"]
 
         class EntryPoint(object):
             name = "mytestplugin"
             dist = Dist()
 
             def load(self):
                 raise ImportError("Don't hide me!")
 
         return iter([EntryPoint()])
 
-    monkeypatch.setattr(pkg_resources, 'iter_entry_points', my_iter)
+    monkeypatch.setattr(pkg_resources, "iter_entry_points", my_iter)
     with pytest.raises(ImportError):
         testdir.parseconfig()
 
 
-@pytest.mark.parametrize('block_it', [True, False])
+@pytest.mark.parametrize("block_it", [True, False])
 def test_plugin_preparse_prevents_setuptools_loading(testdir, monkeypatch, block_it):
     pkg_resources = pytest.importorskip("pkg_resources")
 
     plugin_module_placeholder = object()
 
     def my_iter(name):
         assert name == "pytest11"
 
         class Dist(object):
-            project_name = 'spam'
-            version = '1.0'
+            project_name = "spam"
+            version = "1.0"
 
             def _get_metadata(self, name):
-                return ['foo.txt,sha256=abc,123']
+                return ["foo.txt,sha256=abc,123"]
 
         class EntryPoint(object):
             name = "mytestplugin"
             dist = Dist()
 
             def load(self):
                 return plugin_module_placeholder
 
         return iter([EntryPoint()])
 
-    monkeypatch.setattr(pkg_resources, 'iter_entry_points', my_iter)
+    monkeypatch.setattr(pkg_resources, "iter_entry_points", my_iter)
     args = ("-p", "no:mytestplugin") if block_it else ()
     config = testdir.parseconfig(*args)
     config.pluginmanager.import_plugin("mytestplugin")
     if block_it:
         assert "mytestplugin" not in sys.modules
-        assert config.pluginmanager.get_plugin('mytestplugin') is None
+        assert config.pluginmanager.get_plugin("mytestplugin") is None
     else:
-        assert config.pluginmanager.get_plugin('mytestplugin') is plugin_module_placeholder
+        assert config.pluginmanager.get_plugin(
+            "mytestplugin"
+        ) is plugin_module_placeholder
 
 
 def test_cmdline_processargs_simple(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         def pytest_cmdline_preparse(args):
             args.append("-h")
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        "*pytest*",
-        "*-h*",
-    ])
+    result.stdout.fnmatch_lines(["*pytest*", "*-h*"])
 
 
 def test_invalid_options_show_extra_information(testdir):
     """display extra information when pytest exits due to unrecognized
     options in the command-line"""
-    testdir.makeini("""
+    testdir.makeini(
+        """
         [pytest]
         addopts = --invalid-option
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stderr.fnmatch_lines([
-        "*error: unrecognized arguments: --invalid-option*",
-        "*  inifile: %s*" % testdir.tmpdir.join('tox.ini'),
-        "*  rootdir: %s*" % testdir.tmpdir,
-    ])
+    result.stderr.fnmatch_lines(
+        [
+            "*error: unrecognized arguments: --invalid-option*",
+            "*  inifile: %s*" % testdir.tmpdir.join("tox.ini"),
+            "*  rootdir: %s*" % testdir.tmpdir,
+        ]
+    )
 
 
-@pytest.mark.parametrize('args', [
-    ['dir1', 'dir2', '-v'],
-    ['dir1', '-v', 'dir2'],
-    ['dir2', '-v', 'dir1'],
-    ['-v', 'dir2', 'dir1'],
-])
+@pytest.mark.parametrize(
+    "args",
+    [
+        ["dir1", "dir2", "-v"],
+        ["dir1", "-v", "dir2"],
+        ["dir2", "-v", "dir1"],
+        ["-v", "dir2", "dir1"],
+    ],
+)
 def test_consider_args_after_options_for_rootdir_and_inifile(testdir, args):
     """
     Consider all arguments in the command-line for rootdir and inifile
     discovery, even if they happen to occur after an option. #949
     """
     # replace "dir1" and "dir2" from "args" into their real directory
-    root = testdir.tmpdir.mkdir('myroot')
-    d1 = root.mkdir('dir1')
-    d2 = root.mkdir('dir2')
+    root = testdir.tmpdir.mkdir("myroot")
+    d1 = root.mkdir("dir1")
+    d2 = root.mkdir("dir2")
     for i, arg in enumerate(args):
-        if arg == 'dir1':
+        if arg == "dir1":
             args[i] = d1
-        elif arg == 'dir2':
+        elif arg == "dir2":
             args[i] = d2
     with root.as_cwd():
         result = testdir.runpytest(*args)
-    result.stdout.fnmatch_lines(['*rootdir: *myroot, inifile:'])
+    result.stdout.fnmatch_lines(["*rootdir: *myroot, inifile:"])
 
 
 @pytest.mark.skipif("sys.platform == 'win32'")
 def test_toolongargs_issue224(testdir):
     result = testdir.runpytest("-m", "hello" * 500)
     assert result.ret == EXIT_NOTESTSCOLLECTED
 
 
 def test_config_in_subdirectory_colon_command_line_issue2148(testdir):
-    conftest_source = '''
+    conftest_source = """
         def pytest_addoption(parser):
             parser.addini('foo', 'foo')
-    '''
+    """
 
-    testdir.makefile('.ini', **{
-        'pytest': '[pytest]\nfoo = root',
-        'subdir/pytest': '[pytest]\nfoo = subdir',
-    })
+    testdir.makefile(
+        ".ini",
+        **{"pytest": "[pytest]\nfoo = root", "subdir/pytest": "[pytest]\nfoo = subdir"}
+    )
 
-    testdir.makepyfile(**{
-        'conftest': conftest_source,
-        'subdir/conftest': conftest_source,
-        'subdir/test_foo': '''
+    testdir.makepyfile(
+        **{
+            "conftest": conftest_source,
+            "subdir/conftest": conftest_source,
+            "subdir/test_foo": """
             def test_foo(pytestconfig):
                 assert pytestconfig.getini('foo') == 'subdir'
-        '''})
+        """,
+        }
+    )
 
-    result = testdir.runpytest('subdir/test_foo.py::test_foo')
+    result = testdir.runpytest("subdir/test_foo.py::test_foo")
     assert result.ret == 0
 
 
 def test_notify_exception(testdir, capfd):
     config = testdir.parseconfig()
     excinfo = pytest.raises(ValueError, "raise ValueError(1)")
     config.notify_exception(excinfo)
     out, err = capfd.readouterr()
     assert "ValueError" in err
 
     class A(object):
+
         def pytest_internalerror(self, excrepr):
             return True
 
     config.pluginmanager.register(A())
     config.notify_exception(excinfo)
     out, err = capfd.readouterr()
     assert not err
 
 
 def test_load_initial_conftest_last_ordering(testdir):
     from _pytest.config import get_config
+
     pm = get_config().pluginmanager
 
     class My(object):
+
         def pytest_load_initial_conftests(self):
             pass
 
     m = My()
     pm.register(m)
     hc = pm.hook.pytest_load_initial_conftests
     values = hc._nonwrappers + hc._wrappers
-    expected = [
-        "_pytest.config",
-        'test_config',
-        '_pytest.capture',
-    ]
+    expected = ["_pytest.config", "test_config", "_pytest.capture"]
     assert [x.function.__module__ for x in values] == expected
 
 
 def test_get_plugin_specs_as_list():
     from _pytest.config import _get_plugin_specs_as_list
+
     with pytest.raises(pytest.UsageError):
-        _get_plugin_specs_as_list(set(['foo']))
+        _get_plugin_specs_as_list({"foo"})
     with pytest.raises(pytest.UsageError):
         _get_plugin_specs_as_list(dict())
 
     assert _get_plugin_specs_as_list(None) == []
-    assert _get_plugin_specs_as_list('') == []
-    assert _get_plugin_specs_as_list('foo') == ['foo']
-    assert _get_plugin_specs_as_list('foo,bar') == ['foo', 'bar']
-    assert _get_plugin_specs_as_list(['foo', 'bar']) == ['foo', 'bar']
-    assert _get_plugin_specs_as_list(('foo', 'bar')) == ['foo', 'bar']
+    assert _get_plugin_specs_as_list("") == []
+    assert _get_plugin_specs_as_list("foo") == ["foo"]
+    assert _get_plugin_specs_as_list("foo,bar") == ["foo", "bar"]
+    assert _get_plugin_specs_as_list(["foo", "bar"]) == ["foo", "bar"]
+    assert _get_plugin_specs_as_list(("foo", "bar")) == ["foo", "bar"]
 
 
 class TestWarning(object):
+
     def test_warn_config(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             values = []
             def pytest_configure(config):
                 config.warn("C1", "hello")
             def pytest_logwarning(code, message):
                 if message == "hello" and code == "C1":
                     values.append(1)
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             def test_proper(pytestconfig):
                 import conftest
                 assert conftest.values == [1]
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
     def test_warn_on_test_item_from_request(self, testdir, request):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def fix(request):
                 request.node.warn("T1", "hello")
 
             def test_hello(fix):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest("--disable-pytest-warnings")
         assert result.parseoutcomes()["warnings"] > 0
         assert "hello" not in result.stdout.str()
 
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             ===*warnings summary*===
             *test_warn_on_test_item_from_request.py::test_hello*
             *hello*
-        """)
+        """
+        )
 
 
 class TestRootdir(object):
+
     def test_simple_noini(self, tmpdir):
         assert get_common_ancestor([tmpdir]) == tmpdir
         a = tmpdir.mkdir("a")
         assert get_common_ancestor([a, tmpdir]) == tmpdir
         assert get_common_ancestor([tmpdir, a]) == tmpdir
         with tmpdir.as_cwd():
             assert get_common_ancestor([]) == tmpdir
-            no_path = tmpdir.join('does-not-exist')
+            no_path = tmpdir.join("does-not-exist")
             assert get_common_ancestor([no_path]) == tmpdir
-            assert get_common_ancestor([no_path.join('a')]) == tmpdir
+            assert get_common_ancestor([no_path.join("a")]) == tmpdir
 
     @pytest.mark.parametrize("name", "setup.cfg tox.ini pytest.ini".split())
     def test_with_ini(self, tmpdir, name):
         inifile = tmpdir.join(name)
         inifile.write("[pytest]\n")
 
         a = tmpdir.mkdir("a")
         b = a.mkdir("b")
@@ -724,106 +858,146 @@ class TestRootdir(object):
 
     def test_with_specific_inifile(self, tmpdir):
         inifile = tmpdir.ensure("pytest.ini")
         rootdir, inifile, inicfg = determine_setup(inifile, [tmpdir])
         assert rootdir == tmpdir
 
 
 class TestOverrideIniArgs(object):
+
     @pytest.mark.parametrize("name", "setup.cfg tox.ini pytest.ini".split())
     def test_override_ini_names(self, testdir, name):
-        testdir.tmpdir.join(name).write(py.std.textwrap.dedent("""
+        testdir.tmpdir.join(name).write(
+            textwrap.dedent(
+                """
             [pytest]
-            custom = 1.0"""))
-        testdir.makeconftest("""
+            custom = 1.0"""
+            )
+        )
+        testdir.makeconftest(
+            """
             def pytest_addoption(parser):
-                parser.addini("custom", "")""")
-        testdir.makepyfile("""
+                parser.addini("custom", "")"""
+        )
+        testdir.makepyfile(
+            """
             def test_pass(pytestconfig):
                 ini_val = pytestconfig.getini("custom")
-                print('\\ncustom_option:%s\\n' % ini_val)""")
+                print('\\ncustom_option:%s\\n' % ini_val)"""
+        )
 
         result = testdir.runpytest("--override-ini", "custom=2.0", "-s")
         assert result.ret == 0
         result.stdout.fnmatch_lines(["custom_option:2.0"])
 
-        result = testdir.runpytest("--override-ini", "custom=2.0",
-                                   "--override-ini=custom=3.0", "-s")
+        result = testdir.runpytest(
+            "--override-ini", "custom=2.0", "--override-ini=custom=3.0", "-s"
+        )
         assert result.ret == 0
         result.stdout.fnmatch_lines(["custom_option:3.0"])
 
     def test_override_ini_pathlist(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_addoption(parser):
-                parser.addini("paths", "my new ini value", type="pathlist")""")
-        testdir.makeini("""
+                parser.addini("paths", "my new ini value", type="pathlist")"""
+        )
+        testdir.makeini(
+            """
             [pytest]
-            paths=blah.py""")
-        testdir.makepyfile("""
+            paths=blah.py"""
+        )
+        testdir.makepyfile(
+            """
             import py.path
             def test_pathlist(pytestconfig):
                 config_paths = pytestconfig.getini("paths")
                 print(config_paths)
                 for cpf in config_paths:
-                    print('\\nuser_path:%s' % cpf.basename)""")
-        result = testdir.runpytest("--override-ini",
-                                   'paths=foo/bar1.py foo/bar2.py', "-s")
-        result.stdout.fnmatch_lines(["user_path:bar1.py",
-                                     "user_path:bar2.py"])
+                    print('\\nuser_path:%s' % cpf.basename)"""
+        )
+        result = testdir.runpytest(
+            "--override-ini", "paths=foo/bar1.py foo/bar2.py", "-s"
+        )
+        result.stdout.fnmatch_lines(["user_path:bar1.py", "user_path:bar2.py"])
 
     def test_override_multiple_and_default(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_addoption(parser):
                 addini = parser.addini
                 addini("custom_option_1", "", default="o1")
                 addini("custom_option_2", "", default="o2")
                 addini("custom_option_3", "", default=False, type="bool")
-                addini("custom_option_4", "", default=True, type="bool")""")
-        testdir.makeini("""
+                addini("custom_option_4", "", default=True, type="bool")"""
+        )
+        testdir.makeini(
+            """
             [pytest]
             custom_option_1=custom_option_1
-            custom_option_2=custom_option_2""")
-        testdir.makepyfile("""
+            custom_option_2=custom_option_2
+        """
+        )
+        testdir.makepyfile(
+            """
             def test_multiple_options(pytestconfig):
                 prefix = "custom_option"
                 for x in range(1, 5):
                     ini_value=pytestconfig.getini("%s_%d" % (prefix, x))
-                    print('\\nini%d:%s' % (x, ini_value))""")
+                    print('\\nini%d:%s' % (x, ini_value))
+        """
+        )
         result = testdir.runpytest(
-            "--override-ini", 'custom_option_1=fulldir=/tmp/user1',
-            'custom_option_2=url=/tmp/user2?a=b&d=e',
-            "-o", 'custom_option_3=True',
-            "-o", 'custom_option_4=no', "-s")
-        result.stdout.fnmatch_lines(["ini1:fulldir=/tmp/user1",
-                                     "ini2:url=/tmp/user2?a=b&d=e",
-                                     "ini3:True",
-                                     "ini4:False"])
+            "--override-ini",
+            "custom_option_1=fulldir=/tmp/user1",
+            "-o",
+            "custom_option_2=url=/tmp/user2?a=b&d=e",
+            "-o",
+            "custom_option_3=True",
+            "-o",
+            "custom_option_4=no",
+            "-s",
+        )
+        result.stdout.fnmatch_lines(
+            [
+                "ini1:fulldir=/tmp/user1",
+                "ini2:url=/tmp/user2?a=b&d=e",
+                "ini3:True",
+                "ini4:False",
+            ]
+        )
 
     def test_override_ini_usage_error_bad_style(self, testdir):
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
             xdist_strict=False
-        """)
-        result = testdir.runpytest("--override-ini", 'xdist_strict True', "-s")
+        """
+        )
+        result = testdir.runpytest("--override-ini", "xdist_strict True", "-s")
         result.stderr.fnmatch_lines(["*ERROR* *expects option=value*"])
 
-    @pytest.mark.parametrize('with_ini', [True, False])
+    @pytest.mark.parametrize("with_ini", [True, False])
     def test_override_ini_handled_asap(self, testdir, with_ini):
         """-o should be handled as soon as possible and always override what's in ini files (#2238)"""
         if with_ini:
-            testdir.makeini("""
+            testdir.makeini(
+                """
                 [pytest]
                 python_files=test_*.py
-            """)
-        testdir.makepyfile(unittest_ini_handle="""
+            """
+            )
+        testdir.makepyfile(
+            unittest_ini_handle="""
             def test():
                 pass
-        """)
-        result = testdir.runpytest("--override-ini", 'python_files=unittest_*.py')
+        """
+        )
+        result = testdir.runpytest("--override-ini", "python_files=unittest_*.py")
         result.stdout.fnmatch_lines(["*1 passed in*"])
 
     def test_with_arg_outside_cwd_without_inifile(self, tmpdir, monkeypatch):
         monkeypatch.chdir(str(tmpdir))
         a = tmpdir.mkdir("a")
         b = tmpdir.mkdir("b")
         rootdir, inifile, inicfg = determine_setup(None, [a, b])
         assert rootdir == tmpdir
@@ -832,31 +1006,63 @@ class TestOverrideIniArgs(object):
     def test_with_arg_outside_cwd_with_inifile(self, tmpdir):
         a = tmpdir.mkdir("a")
         b = tmpdir.mkdir("b")
         inifile = a.ensure("pytest.ini")
         rootdir, parsed_inifile, inicfg = determine_setup(None, [a, b])
         assert rootdir == a
         assert inifile == parsed_inifile
 
-    @pytest.mark.parametrize('dirs', ([], ['does-not-exist'],
-                                      ['a/does-not-exist']))
+    @pytest.mark.parametrize("dirs", ([], ["does-not-exist"], ["a/does-not-exist"]))
     def test_with_non_dir_arg(self, dirs, tmpdir):
         with tmpdir.ensure(dir=True).as_cwd():
             rootdir, inifile, inicfg = determine_setup(None, dirs)
             assert rootdir == tmpdir
             assert inifile is None
 
     def test_with_existing_file_in_subdir(self, tmpdir):
         a = tmpdir.mkdir("a")
         a.ensure("exist")
         with tmpdir.as_cwd():
-            rootdir, inifile, inicfg = determine_setup(None, ['a/exist'])
+            rootdir, inifile, inicfg = determine_setup(None, ["a/exist"])
             assert rootdir == tmpdir
             assert inifile is None
 
-    def test_addopts_before_initini(self, testdir, tmpdir, monkeypatch):
-        cache_dir = '.custom_cache'
-        monkeypatch.setenv('PYTEST_ADDOPTS', '-o cache_dir=%s' % cache_dir)
+    def test_addopts_before_initini(self, monkeypatch):
+        cache_dir = ".custom_cache"
+        monkeypatch.setenv("PYTEST_ADDOPTS", "-o cache_dir=%s" % cache_dir)
         from _pytest.config import get_config
+
         config = get_config()
         config._preparse([], addopts=True)
-        assert config._override_ini == [['cache_dir=%s' % cache_dir]]
+        assert config._override_ini == ["cache_dir=%s" % cache_dir]
+
+    def test_override_ini_does_not_contain_paths(self):
+        """Check that -o no longer swallows all options after it (#3103)"""
+        from _pytest.config import get_config
+
+        config = get_config()
+        config._preparse(["-o", "cache_dir=/cache", "/some/test/path"])
+        assert config._override_ini == ["cache_dir=/cache"]
+
+    def test_multiple_override_ini_options(self, testdir, request):
+        """Ensure a file path following a '-o' option does not generate an error (#3103)"""
+        testdir.makepyfile(
+            **{
+                "conftest.py": """
+                def pytest_addoption(parser):
+                    parser.addini('foo', default=None, help='some option')
+                    parser.addini('bar', default=None, help='some option')
+            """,
+                "test_foo.py": """
+                def test(pytestconfig):
+                    assert pytestconfig.getini('foo') == '1'
+                    assert pytestconfig.getini('bar') == '0'
+            """,
+                "test_bar.py": """
+                def test():
+                    assert False
+            """,
+            }
+        )
+        result = testdir.runpytest("-o", "foo=1", "-o", "bar=0", "test_foo.py")
+        assert "ERROR:" not in result.stderr.str()
+        result.stdout.fnmatch_lines(["collected 1 item", "*= 1 passed in *="])
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_conftest.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_conftest.py
@@ -6,61 +6,66 @@ import py
 import pytest
 from _pytest.config import PytestPluginManager
 from _pytest.main import EXIT_NOTESTSCOLLECTED, EXIT_USAGEERROR
 
 
 @pytest.fixture(scope="module", params=["global", "inpackage"])
 def basedir(request, tmpdir_factory):
     from _pytest.tmpdir import tmpdir
+
     tmpdir = tmpdir(request, tmpdir_factory)
     tmpdir.ensure("adir/conftest.py").write("a=1 ; Directory = 3")
     tmpdir.ensure("adir/b/conftest.py").write("b=2 ; a = 1.5")
     if request.param == "inpackage":
         tmpdir.ensure("adir/__init__.py")
         tmpdir.ensure("adir/b/__init__.py")
     return tmpdir
 
 
 def ConftestWithSetinitial(path):
     conftest = PytestPluginManager()
     conftest_setinitial(conftest, [path])
     return conftest
 
 
 def conftest_setinitial(conftest, args, confcutdir=None):
+
     class Namespace(object):
+
         def __init__(self):
             self.file_or_dir = args
             self.confcutdir = str(confcutdir)
             self.noconftest = False
+
     conftest._set_initial_conftests(Namespace())
 
 
 class TestConftestValueAccessGlobal(object):
+
     def test_basic_init(self, basedir):
         conftest = PytestPluginManager()
         p = basedir.join("adir")
         assert conftest._rget_with_confmod("a", p)[1] == 1
 
     def test_immediate_initialiation_and_incremental_are_the_same(self, basedir):
         conftest = PytestPluginManager()
         len(conftest._path2confmods)
         conftest._getconftestmodules(basedir)
         snap1 = len(conftest._path2confmods)
         # assert len(conftest._path2confmods) == snap1 + 1
-        conftest._getconftestmodules(basedir.join('adir'))
+        conftest._getconftestmodules(basedir.join("adir"))
         assert len(conftest._path2confmods) == snap1 + 1
-        conftest._getconftestmodules(basedir.join('b'))
+        conftest._getconftestmodules(basedir.join("b"))
         assert len(conftest._path2confmods) == snap1 + 2
 
     def test_value_access_not_existing(self, basedir):
         conftest = ConftestWithSetinitial(basedir)
         with pytest.raises(KeyError):
-            conftest._rget_with_confmod('a', basedir)
+            conftest._rget_with_confmod("a", basedir)
 
     def test_value_access_by_path(self, basedir):
         conftest = ConftestWithSetinitial(basedir)
         adir = basedir.join("adir")
         assert conftest._rget_with_confmod("a", adir)[1] == 1
         assert conftest._rget_with_confmod("a", adir.join("b"))[1] == 1.5
 
     def test_value_access_with_confmod(self, basedir):
@@ -79,17 +84,17 @@ def test_conftest_in_nonpkg_with_init(tm
     tmpdir.ensure("adir-1.0/b/conftest.py").write("b=2 ; a = 1.5")
     tmpdir.ensure("adir-1.0/b/__init__.py")
     tmpdir.ensure("adir-1.0/__init__.py")
     ConftestWithSetinitial(tmpdir.join("adir-1.0", "b"))
 
 
 def test_doubledash_considered(testdir):
     conf = testdir.mkdir("--option")
-    conf.join("conftest.py").ensure()
+    conf.ensure("conftest.py")
     conftest = PytestPluginManager()
     conftest_setinitial(conftest, [conf.basename, conf.basename])
     values = conftest._getconftestmodules(conf)
     assert len(values) == 1
 
 
 def test_issue151_load_all_conftests(testdir):
     names = "code proj src".split()
@@ -100,32 +105,34 @@ def test_issue151_load_all_conftests(tes
     conftest = PytestPluginManager()
     conftest_setinitial(conftest, names)
     d = list(conftest._conftestpath2mod.values())
     assert len(d) == len(names)
 
 
 def test_conftest_global_import(testdir):
     testdir.makeconftest("x=3")
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         import py, pytest
         from _pytest.config import PytestPluginManager
         conf = PytestPluginManager()
         mod = conf._importconftest(py.path.local("conftest.py"))
         assert mod.x == 3
         import conftest
         assert conftest is mod, (conftest, mod)
         subconf = py.path.local().ensure("sub", "conftest.py")
         subconf.write("y=4")
         mod2 = conf._importconftest(subconf)
         assert mod != mod2
         assert mod2.y == 4
         import conftest
         assert conftest is mod2, (conftest, mod)
-    """)
+    """
+    )
     res = testdir.runpython(p)
     assert res.ret == 0
 
 
 def test_conftestcutdir(testdir):
     conf = testdir.makeconftest("")
     p = testdir.mkdir("x")
     conftest = PytestPluginManager()
@@ -149,330 +156,388 @@ def test_conftestcutdir_inplace_consider
     conf = testdir.makeconftest("")
     conftest = PytestPluginManager()
     conftest_setinitial(conftest, [conf.dirpath()], confcutdir=conf.dirpath())
     values = conftest._getconftestmodules(conf.dirpath())
     assert len(values) == 1
     assert values[0].__file__.startswith(str(conf))
 
 
-@pytest.mark.parametrize("name", 'test tests whatever .dotdir'.split())
+@pytest.mark.parametrize("name", "test tests whatever .dotdir".split())
 def test_setinitial_conftest_subdirs(testdir, name):
     sub = testdir.mkdir(name)
     subconftest = sub.ensure("conftest.py")
     conftest = PytestPluginManager()
     conftest_setinitial(conftest, [sub.dirpath()], confcutdir=testdir.tmpdir)
-    if name not in ('whatever', '.dotdir'):
+    if name not in ("whatever", ".dotdir"):
         assert subconftest in conftest._conftestpath2mod
         assert len(conftest._conftestpath2mod) == 1
     else:
         assert subconftest not in conftest._conftestpath2mod
         assert len(conftest._conftestpath2mod) == 0
 
 
 def test_conftest_confcutdir(testdir):
     testdir.makeconftest("assert 0")
     x = testdir.mkdir("x")
-    x.join("conftest.py").write(_pytest._code.Source("""
+    x.join("conftest.py").write(
+        _pytest._code.Source(
+            """
         def pytest_addoption(parser):
             parser.addoption("--xyz", action="store_true")
-    """))
+    """
+        )
+    )
     result = testdir.runpytest("-h", "--confcutdir=%s" % x, x)
     result.stdout.fnmatch_lines(["*--xyz*"])
-    assert 'warning: could not load initial' not in result.stdout.str()
+    assert "warning: could not load initial" not in result.stdout.str()
 
 
 def test_no_conftest(testdir):
     testdir.makeconftest("assert 0")
     result = testdir.runpytest("--noconftest")
     assert result.ret == EXIT_NOTESTSCOLLECTED
 
     result = testdir.runpytest()
     assert result.ret == EXIT_USAGEERROR
 
 
 def test_conftest_existing_resultlog(testdir):
     x = testdir.mkdir("tests")
-    x.join("conftest.py").write(_pytest._code.Source("""
+    x.join("conftest.py").write(
+        _pytest._code.Source(
+            """
         def pytest_addoption(parser):
             parser.addoption("--xyz", action="store_true")
-    """))
+    """
+        )
+    )
     testdir.makefile(ext=".log", result="")  # Writes result.log
     result = testdir.runpytest("-h", "--resultlog", "result.log")
     result.stdout.fnmatch_lines(["*--xyz*"])
 
 
 def test_conftest_existing_junitxml(testdir):
     x = testdir.mkdir("tests")
-    x.join("conftest.py").write(_pytest._code.Source("""
+    x.join("conftest.py").write(
+        _pytest._code.Source(
+            """
         def pytest_addoption(parser):
             parser.addoption("--xyz", action="store_true")
-    """))
+    """
+        )
+    )
     testdir.makefile(ext=".xml", junit="")  # Writes junit.xml
     result = testdir.runpytest("-h", "--junitxml", "junit.xml")
     result.stdout.fnmatch_lines(["*--xyz*"])
 
 
 def test_conftest_import_order(testdir, monkeypatch):
     ct1 = testdir.makeconftest("")
     sub = testdir.mkdir("sub")
     ct2 = sub.join("conftest.py")
     ct2.write("")
 
     def impct(p):
         return p
 
     conftest = PytestPluginManager()
     conftest._confcutdir = testdir.tmpdir
-    monkeypatch.setattr(conftest, '_importconftest', impct)
+    monkeypatch.setattr(conftest, "_importconftest", impct)
     assert conftest._getconftestmodules(sub) == [ct1, ct2]
 
 
 def test_fixture_dependency(testdir, monkeypatch):
     ct1 = testdir.makeconftest("")
     ct1 = testdir.makepyfile("__init__.py")
     ct1.write("")
     sub = testdir.mkdir("sub")
     sub.join("__init__.py").write("")
-    sub.join("conftest.py").write(py.std.textwrap.dedent("""
+    sub.join("conftest.py").write(
+        dedent(
+            """
         import pytest
 
         @pytest.fixture
         def not_needed():
             assert False, "Should not be called!"
 
         @pytest.fixture
         def foo():
             assert False, "Should not be called!"
 
         @pytest.fixture
         def bar(foo):
             return 'bar'
-    """))
+    """
+        )
+    )
     subsub = sub.mkdir("subsub")
     subsub.join("__init__.py").write("")
-    subsub.join("test_bar.py").write(py.std.textwrap.dedent("""
+    subsub.join("test_bar.py").write(
+        dedent(
+            """
         import pytest
 
         @pytest.fixture
         def bar():
             return 'sub bar'
 
         def test_event_fixture(bar):
             assert bar == 'sub bar'
-    """))
+    """
+        )
+    )
     result = testdir.runpytest("sub")
     result.stdout.fnmatch_lines(["*1 passed*"])
 
 
 def test_conftest_found_with_double_dash(testdir):
     sub = testdir.mkdir("sub")
-    sub.join("conftest.py").write(py.std.textwrap.dedent("""
+    sub.join("conftest.py").write(
+        dedent(
+            """
         def pytest_addoption(parser):
             parser.addoption("--hello-world", action="store_true")
-    """))
+    """
+        )
+    )
     p = sub.join("test_hello.py")
-    p.write(py.std.textwrap.dedent("""
-        import pytest
-        def test_hello(found):
-            assert found == 1
-    """))
+    p.write("def test_hello(): pass")
     result = testdir.runpytest(str(p) + "::test_hello", "-h")
-    result.stdout.fnmatch_lines("""
+    result.stdout.fnmatch_lines(
+        """
         *--hello-world*
-    """)
+    """
+    )
 
 
 class TestConftestVisibility(object):
+
     def _setup_tree(self, testdir):  # for issue616
         # example mostly taken from:
         # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html
         runner = testdir.mkdir("empty")
         package = testdir.mkdir("package")
 
-        package.join("conftest.py").write(dedent("""\
+        package.join("conftest.py").write(
+            dedent(
+                """\
             import pytest
             @pytest.fixture
             def fxtr():
                 return "from-package"
-        """))
-        package.join("test_pkgroot.py").write(dedent("""\
+        """
+            )
+        )
+        package.join("test_pkgroot.py").write(
+            dedent(
+                """\
             def test_pkgroot(fxtr):
                 assert fxtr == "from-package"
-        """))
+        """
+            )
+        )
 
         swc = package.mkdir("swc")
         swc.join("__init__.py").ensure()
-        swc.join("conftest.py").write(dedent("""\
+        swc.join("conftest.py").write(
+            dedent(
+                """\
             import pytest
             @pytest.fixture
             def fxtr():
                 return "from-swc"
-        """))
-        swc.join("test_with_conftest.py").write(dedent("""\
+        """
+            )
+        )
+        swc.join("test_with_conftest.py").write(
+            dedent(
+                """\
             def test_with_conftest(fxtr):
                 assert fxtr == "from-swc"
 
-        """))
+        """
+            )
+        )
 
         snc = package.mkdir("snc")
         snc.join("__init__.py").ensure()
-        snc.join("test_no_conftest.py").write(dedent("""\
+        snc.join("test_no_conftest.py").write(
+            dedent(
+                """\
             def test_no_conftest(fxtr):
                 assert fxtr == "from-package"   # No local conftest.py, so should
                                                 # use value from parent dir's
 
-        """))
+        """
+            )
+        )
         print("created directory structure:")
         for x in testdir.tmpdir.visit():
             print("   " + x.relto(testdir.tmpdir))
 
-        return {
-            "runner": runner,
-            "package": package,
-            "swc": swc,
-            "snc": snc}
+        return {"runner": runner, "package": package, "swc": swc, "snc": snc}
 
     # N.B.: "swc" stands for "subdir with conftest.py"
     #       "snc" stands for "subdir no [i.e. without] conftest.py"
-    @pytest.mark.parametrize("chdir,testarg,expect_ntests_passed", [
-        # Effective target: package/..
-        ("runner", "..", 3),
-        ("package", "..", 3),
-        ("swc", "../..", 3),
-        ("snc", "../..", 3),
-
-        # Effective target: package
-        ("runner", "../package", 3),
-        ("package", ".", 3),
-        ("swc", "..", 3),
-        ("snc", "..", 3),
-
-        # Effective target: package/swc
-        ("runner", "../package/swc", 1),
-        ("package", "./swc", 1),
-        ("swc", ".", 1),
-        ("snc", "../swc", 1),
-
-        # Effective target: package/snc
-        ("runner", "../package/snc", 1),
-        ("package", "./snc", 1),
-        ("swc", "../snc", 1),
-        ("snc", ".", 1),
-    ])
+    @pytest.mark.parametrize(
+        "chdir,testarg,expect_ntests_passed",
+        [
+            # Effective target: package/..
+            ("runner", "..", 3),
+            ("package", "..", 3),
+            ("swc", "../..", 3),
+            ("snc", "../..", 3),
+            # Effective target: package
+            ("runner", "../package", 3),
+            ("package", ".", 3),
+            ("swc", "..", 3),
+            ("snc", "..", 3),
+            # Effective target: package/swc
+            ("runner", "../package/swc", 1),
+            ("package", "./swc", 1),
+            ("swc", ".", 1),
+            ("snc", "../swc", 1),
+            # Effective target: package/snc
+            ("runner", "../package/snc", 1),
+            ("package", "./snc", 1),
+            ("swc", "../snc", 1),
+            ("snc", ".", 1),
+        ],
+    )
     @pytest.mark.issue616
     def test_parsefactories_relative_node_ids(
-            self, testdir, chdir, testarg, expect_ntests_passed):
+        self, testdir, chdir, testarg, expect_ntests_passed
+    ):
         dirs = self._setup_tree(testdir)
-        print("pytest run in cwd: %s" % (
-              dirs[chdir].relto(testdir.tmpdir)))
+        print("pytest run in cwd: %s" % (dirs[chdir].relto(testdir.tmpdir)))
         print("pytestarg        : %s" % (testarg))
         print("expected pass    : %s" % (expect_ntests_passed))
         with dirs[chdir].as_cwd():
             reprec = testdir.inline_run(testarg, "-q", "--traceconfig")
             reprec.assertoutcome(passed=expect_ntests_passed)
 
 
-@pytest.mark.parametrize('confcutdir,passed,error', [
-    ('.', 2, 0),
-    ('src', 1, 1),
-    (None, 1, 1),
-])
+@pytest.mark.parametrize(
+    "confcutdir,passed,error", [(".", 2, 0), ("src", 1, 1), (None, 1, 1)]
+)
 def test_search_conftest_up_to_inifile(testdir, confcutdir, passed, error):
-    """Test that conftest files are detected only up to a ini file, unless
+    """Test that conftest files are detected only up to an ini file, unless
     an explicit --confcutdir option is given.
     """
     root = testdir.tmpdir
-    src = root.join('src').ensure(dir=1)
-    src.join('pytest.ini').write('[pytest]')
-    src.join('conftest.py').write(_pytest._code.Source("""
+    src = root.join("src").ensure(dir=1)
+    src.join("pytest.ini").write("[pytest]")
+    src.join("conftest.py").write(
+        _pytest._code.Source(
+            """
         import pytest
         @pytest.fixture
         def fix1(): pass
-    """))
-    src.join('test_foo.py').write(_pytest._code.Source("""
+    """
+        )
+    )
+    src.join("test_foo.py").write(
+        _pytest._code.Source(
+            """
         def test_1(fix1):
             pass
         def test_2(out_of_reach):
             pass
-    """))
-    root.join('conftest.py').write(_pytest._code.Source("""
+    """
+        )
+    )
+    root.join("conftest.py").write(
+        _pytest._code.Source(
+            """
         import pytest
         @pytest.fixture
         def out_of_reach(): pass
-    """))
+    """
+        )
+    )
 
     args = [str(src)]
     if confcutdir:
-        args = ['--confcutdir=%s' % root.join(confcutdir)]
+        args = ["--confcutdir=%s" % root.join(confcutdir)]
     result = testdir.runpytest(*args)
-    match = ''
+    match = ""
     if passed:
-        match += '*%d passed*' % passed
+        match += "*%d passed*" % passed
     if error:
-        match += '*%d error*' % error
+        match += "*%d error*" % error
     result.stdout.fnmatch_lines(match)
 
 
 def test_issue1073_conftest_special_objects(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         class DontTouchMe(object):
             def __getattr__(self, x):
                 raise Exception('cant touch me')
 
         x = DontTouchMe()
-    """)
-    testdir.makepyfile("""
+    """
+    )
+    testdir.makepyfile(
+        """
         def test_some():
             pass
-    """)
+    """
+    )
     res = testdir.runpytest()
     assert res.ret == 0
 
 
 def test_conftest_exception_handling(testdir):
-    testdir.makeconftest('''
+    testdir.makeconftest(
+        """
         raise ValueError()
-    ''')
-    testdir.makepyfile("""
+    """
+    )
+    testdir.makepyfile(
+        """
         def test_some():
             pass
-    """)
+    """
+    )
     res = testdir.runpytest()
     assert res.ret == 4
-    assert 'raise ValueError()' in [line.strip() for line in res.errlines]
+    assert "raise ValueError()" in [line.strip() for line in res.errlines]
 
 
 def test_hook_proxy(testdir):
     """Session's gethookproxy() would cache conftests incorrectly (#2016).
     It was decided to remove the cache altogether.
     """
-    testdir.makepyfile(**{
-        'root/demo-0/test_foo1.py': "def test1(): pass",
-
-        'root/demo-a/test_foo2.py': "def test1(): pass",
-        'root/demo-a/conftest.py': """
+    testdir.makepyfile(
+        **{
+            "root/demo-0/test_foo1.py": "def test1(): pass",
+            "root/demo-a/test_foo2.py": "def test1(): pass",
+            "root/demo-a/conftest.py": """
             def pytest_ignore_collect(path, config):
                 return True
             """,
-
-        'root/demo-b/test_foo3.py': "def test1(): pass",
-        'root/demo-c/test_foo4.py': "def test1(): pass",
-    })
+            "root/demo-b/test_foo3.py": "def test1(): pass",
+            "root/demo-c/test_foo4.py": "def test1(): pass",
+        }
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        '*test_foo1.py*',
-        '*test_foo3.py*',
-        '*test_foo4.py*',
-        '*3 passed*',
-    ])
+    result.stdout.fnmatch_lines(
+        ["*test_foo1.py*", "*test_foo3.py*", "*test_foo4.py*", "*3 passed*"]
+    )
 
 
 def test_required_option_help(testdir):
     testdir.makeconftest("assert 0")
     x = testdir.mkdir("x")
-    x.join("conftest.py").write(_pytest._code.Source("""
+    x.join("conftest.py").write(
+        _pytest._code.Source(
+            """
         def pytest_addoption(parser):
             parser.addoption("--xyz", action="store_true", required=True)
-    """))
+    """
+        )
+    )
     result = testdir.runpytest("-h", x)
-    assert 'argument --xyz is required' not in result.stdout.str()
-    assert 'general:' in result.stdout.str()
+    assert "argument --xyz is required" not in result.stdout.str()
+    assert "general:" in result.stdout.str()
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_doctest.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_doctest.py
@@ -6,183 +6,194 @@ from _pytest.compat import MODULE_NOT_FO
 from _pytest.doctest import DoctestItem, DoctestModule, DoctestTextfile
 import pytest
 
 
 class TestDoctests(object):
 
     def test_collect_testtextfile(self, testdir):
         w = testdir.maketxtfile(whatever="")
-        checkfile = testdir.maketxtfile(test_something="""
+        checkfile = testdir.maketxtfile(
+            test_something="""
             alskdjalsdk
             >>> i = 5
             >>> i-1
             4
-        """)
+        """
+        )
 
         for x in (testdir.tmpdir, checkfile):
             # print "checking that %s returns custom items" % (x,)
             items, reprec = testdir.inline_genitems(x)
             assert len(items) == 1
             assert isinstance(items[0], DoctestItem)
             assert isinstance(items[0].parent, DoctestTextfile)
         # Empty file has no items.
         items, reprec = testdir.inline_genitems(w)
         assert len(items) == 0
 
     def test_collect_module_empty(self, testdir):
         path = testdir.makepyfile(whatever="#")
         for p in (path, testdir.tmpdir):
-            items, reprec = testdir.inline_genitems(p,
-                                                    '--doctest-modules')
+            items, reprec = testdir.inline_genitems(p, "--doctest-modules")
             assert len(items) == 0
 
     def test_collect_module_single_modulelevel_doctest(self, testdir):
         path = testdir.makepyfile(whatever='""">>> pass"""')
         for p in (path, testdir.tmpdir):
-            items, reprec = testdir.inline_genitems(p,
-                                                    '--doctest-modules')
+            items, reprec = testdir.inline_genitems(p, "--doctest-modules")
             assert len(items) == 1
             assert isinstance(items[0], DoctestItem)
             assert isinstance(items[0].parent, DoctestModule)
 
     def test_collect_module_two_doctest_one_modulelevel(self, testdir):
-        path = testdir.makepyfile(whatever="""
+        path = testdir.makepyfile(
+            whatever="""
             '>>> x = None'
             def my_func():
                 ">>> magic = 42 "
-        """)
+        """
+        )
         for p in (path, testdir.tmpdir):
-            items, reprec = testdir.inline_genitems(p,
-                                                    '--doctest-modules')
+            items, reprec = testdir.inline_genitems(p, "--doctest-modules")
             assert len(items) == 2
             assert isinstance(items[0], DoctestItem)
             assert isinstance(items[1], DoctestItem)
             assert isinstance(items[0].parent, DoctestModule)
             assert items[0].parent is items[1].parent
 
     def test_collect_module_two_doctest_no_modulelevel(self, testdir):
-        path = testdir.makepyfile(whatever="""
+        path = testdir.makepyfile(
+            whatever="""
             '# Empty'
             def my_func():
                 ">>> magic = 42 "
             def unuseful():
                 '''
                 # This is a function
                 # >>> # it doesn't have any doctest
                 '''
             def another():
                 '''
                 # This is another function
                 >>> import os # this one does have a doctest
                 '''
-        """)
+        """
+        )
         for p in (path, testdir.tmpdir):
-            items, reprec = testdir.inline_genitems(p,
-                                                    '--doctest-modules')
+            items, reprec = testdir.inline_genitems(p, "--doctest-modules")
             assert len(items) == 2
             assert isinstance(items[0], DoctestItem)
             assert isinstance(items[1], DoctestItem)
             assert isinstance(items[0].parent, DoctestModule)
             assert items[0].parent is items[1].parent
 
     def test_simple_doctestfile(self, testdir):
-        p = testdir.maketxtfile(test_doc="""
+        p = testdir.maketxtfile(
+            test_doc="""
             >>> x = 1
             >>> x == 1
             False
-        """)
-        reprec = testdir.inline_run(p, )
+        """
+        )
+        reprec = testdir.inline_run(p)
         reprec.assertoutcome(failed=1)
 
     def test_new_pattern(self, testdir):
-        p = testdir.maketxtfile(xdoc="""
+        p = testdir.maketxtfile(
+            xdoc="""
             >>> x = 1
             >>> x == 1
             False
-        """)
+        """
+        )
         reprec = testdir.inline_run(p, "--doctest-glob=x*.txt")
         reprec.assertoutcome(failed=1)
 
     def test_multiple_patterns(self, testdir):
         """Test support for multiple --doctest-glob arguments (#1255).
         """
-        testdir.maketxtfile(xdoc="""
+        testdir.maketxtfile(
+            xdoc="""
             >>> 1
             1
-        """)
-        testdir.makefile('.foo', test="""
+        """
+        )
+        testdir.makefile(
+            ".foo",
+            test="""
             >>> 1
             1
-        """)
-        testdir.maketxtfile(test_normal="""
+        """,
+        )
+        testdir.maketxtfile(
+            test_normal="""
             >>> 1
             1
-        """)
-        expected = set(['xdoc.txt', 'test.foo', 'test_normal.txt'])
-        assert set(x.basename for x in testdir.tmpdir.listdir()) == expected
+        """
+        )
+        expected = {"xdoc.txt", "test.foo", "test_normal.txt"}
+        assert {x.basename for x in testdir.tmpdir.listdir()} == expected
         args = ["--doctest-glob=xdoc*.txt", "--doctest-glob=*.foo"]
         result = testdir.runpytest(*args)
-        result.stdout.fnmatch_lines([
-            '*test.foo *',
-            '*xdoc.txt *',
-            '*2 passed*',
-        ])
+        result.stdout.fnmatch_lines(["*test.foo *", "*xdoc.txt *", "*2 passed*"])
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            '*test_normal.txt *',
-            '*1 passed*',
-        ])
+        result.stdout.fnmatch_lines(["*test_normal.txt *", "*1 passed*"])
 
     @pytest.mark.parametrize(
-        '   test_string,    encoding',
-        [
-            (u'foo', 'ascii'),
-            (u'öäü', 'latin1'),
-            (u'öäü', 'utf-8')
-        ]
+        "   test_string,    encoding",
+        [(u"foo", "ascii"), (u"öäü", "latin1"), (u"öäü", "utf-8")],
     )
     def test_encoding(self, testdir, test_string, encoding):
         """Test support for doctest_encoding ini option.
         """
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
-            doctest_encoding={0}
-        """.format(encoding))
+            doctest_encoding={}
+        """.format(
+                encoding
+            )
+        )
         doctest = u"""
-            >>> u"{0}"
-            {1}
-        """.format(test_string, repr(test_string))
+            >>> u"{}"
+            {}
+        """.format(
+            test_string, repr(test_string)
+        )
         testdir._makefile(".txt", [doctest], {}, encoding=encoding)
 
         result = testdir.runpytest()
 
-        result.stdout.fnmatch_lines([
-            '*1 passed*',
-        ])
+        result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_doctest_unexpected_exception(self, testdir):
-        testdir.maketxtfile("""
+        testdir.maketxtfile(
+            """
             >>> i = 0
             >>> 0 / i
             2
-        """)
+        """
+        )
         result = testdir.runpytest("--doctest-modules")
-        result.stdout.fnmatch_lines([
-            "*unexpected_exception*",
-            "*>>> i = 0*",
-            "*>>> 0 / i*",
-            "*UNEXPECTED*ZeroDivision*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*unexpected_exception*",
+                "*>>> i = 0*",
+                "*>>> 0 / i*",
+                "*UNEXPECTED*ZeroDivision*",
+            ]
+        )
 
     def test_docstring_partial_context_around_error(self, testdir):
         """Test that we show some context before the actual line of a failing
         doctest.
         """
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            '''
             def foo():
                 """
                 text-line-1
                 text-line-2
                 text-line-3
                 text-line-4
                 text-line-5
                 text-line-6
@@ -191,199 +202,247 @@ class TestDoctests(object):
                 text-line-9
                 text-line-10
                 text-line-11
                 >>> 1 + 1
                 3
 
                 text-line-after
                 """
-        ''')
-        result = testdir.runpytest('--doctest-modules')
-        result.stdout.fnmatch_lines([
-            '*docstring_partial_context_around_error*',
-            '005*text-line-3',
-            '006*text-line-4',
-            '013*text-line-11',
-            '014*>>> 1 + 1',
-            'Expected:',
-            '    3',
-            'Got:',
-            '    2',
-        ])
+        '''
+        )
+        result = testdir.runpytest("--doctest-modules")
+        result.stdout.fnmatch_lines(
+            [
+                "*docstring_partial_context_around_error*",
+                "005*text-line-3",
+                "006*text-line-4",
+                "013*text-line-11",
+                "014*>>> 1 + 1",
+                "Expected:",
+                "    3",
+                "Got:",
+                "    2",
+            ]
+        )
         # lines below should be trimmed out
-        assert 'text-line-2' not in result.stdout.str()
-        assert 'text-line-after' not in result.stdout.str()
+        assert "text-line-2" not in result.stdout.str()
+        assert "text-line-after" not in result.stdout.str()
 
     def test_docstring_full_context_around_error(self, testdir):
         """Test that we show the whole context before the actual line of a failing
         doctest, provided that the context is up to 10 lines long.
         """
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            '''
             def foo():
                 """
                 text-line-1
                 text-line-2
 
                 >>> 1 + 1
                 3
                 """
-        ''')
-        result = testdir.runpytest('--doctest-modules')
-        result.stdout.fnmatch_lines([
-            '*docstring_full_context_around_error*',
-            '003*text-line-1',
-            '004*text-line-2',
-            '006*>>> 1 + 1',
-            'Expected:',
-            '    3',
-            'Got:',
-            '    2',
-        ])
+        '''
+        )
+        result = testdir.runpytest("--doctest-modules")
+        result.stdout.fnmatch_lines(
+            [
+                "*docstring_full_context_around_error*",
+                "003*text-line-1",
+                "004*text-line-2",
+                "006*>>> 1 + 1",
+                "Expected:",
+                "    3",
+                "Got:",
+                "    2",
+            ]
+        )
 
     def test_doctest_linedata_missing(self, testdir):
-        testdir.tmpdir.join('hello.py').write(_pytest._code.Source("""
+        testdir.tmpdir.join("hello.py").write(
+            _pytest._code.Source(
+                """
             class Fun(object):
                 @property
                 def test(self):
                     '''
                     >>> a = 1
                     >>> 1/0
                     '''
-            """))
+            """
+            )
+        )
         result = testdir.runpytest("--doctest-modules")
-        result.stdout.fnmatch_lines([
-            "*hello*",
-            "*EXAMPLE LOCATION UNKNOWN, not showing all tests of that example*",
-            "*1/0*",
-            "*UNEXPECTED*ZeroDivision*",
-            "*1 failed*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*hello*",
+                "*EXAMPLE LOCATION UNKNOWN, not showing all tests of that example*",
+                "*1/0*",
+                "*UNEXPECTED*ZeroDivision*",
+                "*1 failed*",
+            ]
+        )
 
     def test_doctest_unex_importerror_only_txt(self, testdir):
-        testdir.maketxtfile("""
+        testdir.maketxtfile(
+            """
             >>> import asdalsdkjaslkdjasd
             >>>
-        """)
+        """
+        )
         result = testdir.runpytest()
         # doctest is never executed because of error during hello.py collection
-        result.stdout.fnmatch_lines([
-            "*>>> import asdals*",
-            "*UNEXPECTED*{e}*".format(e=MODULE_NOT_FOUND_ERROR),
-            "{e}: No module named *asdal*".format(e=MODULE_NOT_FOUND_ERROR),
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*>>> import asdals*",
+                "*UNEXPECTED*{e}*".format(e=MODULE_NOT_FOUND_ERROR),
+                "{e}: No module named *asdal*".format(e=MODULE_NOT_FOUND_ERROR),
+            ]
+        )
 
     def test_doctest_unex_importerror_with_module(self, testdir):
-        testdir.tmpdir.join("hello.py").write(_pytest._code.Source("""
+        testdir.tmpdir.join("hello.py").write(
+            _pytest._code.Source(
+                """
             import asdalsdkjaslkdjasd
-        """))
-        testdir.maketxtfile("""
+        """
+            )
+        )
+        testdir.maketxtfile(
+            """
             >>> import hello
             >>>
-        """)
+        """
+        )
         result = testdir.runpytest("--doctest-modules")
         # doctest is never executed because of error during hello.py collection
-        result.stdout.fnmatch_lines([
-            "*ERROR collecting hello.py*",
-            "*{e}: No module named *asdals*".format(e=MODULE_NOT_FOUND_ERROR),
-            "*Interrupted: 1 errors during collection*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*ERROR collecting hello.py*",
+                "*{e}: No module named *asdals*".format(e=MODULE_NOT_FOUND_ERROR),
+                "*Interrupted: 1 errors during collection*",
+            ]
+        )
 
     def test_doctestmodule(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             '''
                 >>> x = 1
                 >>> x == 1
                 False
 
             '''
-        """)
+        """
+        )
         reprec = testdir.inline_run(p, "--doctest-modules")
         reprec.assertoutcome(failed=1)
 
     def test_doctestmodule_external_and_issue116(self, testdir):
         p = testdir.mkpydir("hello")
-        p.join("__init__.py").write(_pytest._code.Source("""
+        p.join("__init__.py").write(
+            _pytest._code.Source(
+                """
             def somefunc():
                 '''
                     >>> i = 0
                     >>> i + 1
                     2
                 '''
-        """))
+        """
+            )
+        )
         result = testdir.runpytest(p, "--doctest-modules")
-        result.stdout.fnmatch_lines([
-            '004 *>>> i = 0',
-            '005 *>>> i + 1',
-            '*Expected:',
-            "*    2",
-            "*Got:",
-            "*    1",
-            "*:5: DocTestFailure"
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "004 *>>> i = 0",
+                "005 *>>> i + 1",
+                "*Expected:",
+                "*    2",
+                "*Got:",
+                "*    1",
+                "*:5: DocTestFailure",
+            ]
+        )
 
     def test_txtfile_failing(self, testdir):
-        p = testdir.maketxtfile("""
+        p = testdir.maketxtfile(
+            """
             >>> i = 0
             >>> i + 1
             2
-        """)
+        """
+        )
         result = testdir.runpytest(p, "-s")
-        result.stdout.fnmatch_lines([
-            '001 >>> i = 0',
-            '002 >>> i + 1',
-            'Expected:',
-            "    2",
-            "Got:",
-            "    1",
-            "*test_txtfile_failing.txt:2: DocTestFailure"
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "001 >>> i = 0",
+                "002 >>> i + 1",
+                "Expected:",
+                "    2",
+                "Got:",
+                "    1",
+                "*test_txtfile_failing.txt:2: DocTestFailure",
+            ]
+        )
 
     def test_txtfile_with_fixtures(self, testdir):
-        p = testdir.maketxtfile("""
+        p = testdir.maketxtfile(
+            """
             >>> dir = getfixture('tmpdir')
             >>> type(dir).__name__
             'LocalPath'
-        """)
-        reprec = testdir.inline_run(p, )
+        """
+        )
+        reprec = testdir.inline_run(p)
         reprec.assertoutcome(passed=1)
 
     def test_txtfile_with_usefixtures_in_ini(self, testdir):
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
             usefixtures = myfixture
-        """)
-        testdir.makeconftest("""
+        """
+        )
+        testdir.makeconftest(
+            """
             import pytest
             @pytest.fixture
             def myfixture(monkeypatch):
                 monkeypatch.setenv("HELLO", "WORLD")
-        """)
+        """
+        )
 
-        p = testdir.maketxtfile("""
+        p = testdir.maketxtfile(
+            """
             >>> import os
             >>> os.environ["HELLO"]
             'WORLD'
-        """)
-        reprec = testdir.inline_run(p, )
+        """
+        )
+        reprec = testdir.inline_run(p)
         reprec.assertoutcome(passed=1)
 
     def test_doctestmodule_with_fixtures(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             '''
                 >>> dir = getfixture('tmpdir')
                 >>> type(dir).__name__
                 'LocalPath'
             '''
-        """)
+        """
+        )
         reprec = testdir.inline_run(p, "--doctest-modules")
         reprec.assertoutcome(passed=1)
 
     def test_doctestmodule_three_tests(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             '''
             >>> dir = getfixture('tmpdir')
             >>> type(dir).__name__
             'LocalPath'
             '''
             def my_func():
                 '''
                 >>> magic = 42
@@ -393,611 +452,755 @@ class TestDoctests(object):
             def unuseful():
                 pass
             def another():
                 '''
                 >>> import os
                 >>> os is os
                 True
                 '''
-        """)
+        """
+        )
         reprec = testdir.inline_run(p, "--doctest-modules")
         reprec.assertoutcome(passed=3)
 
     def test_doctestmodule_two_tests_one_fail(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             class MyClass(object):
                 def bad_meth(self):
                     '''
                     >>> magic = 42
                     >>> magic
                     0
                     '''
                 def nice_meth(self):
                     '''
                     >>> magic = 42
                     >>> magic - 42
                     0
                     '''
-        """)
+        """
+        )
         reprec = testdir.inline_run(p, "--doctest-modules")
         reprec.assertoutcome(failed=1, passed=1)
 
     def test_ignored_whitespace(self, testdir):
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
             doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE
-        """)
-        p = testdir.makepyfile("""
+        """
+        )
+        p = testdir.makepyfile(
+            """
             class MyClass(object):
                 '''
                 >>> a = "foo    "
                 >>> print(a)
                 foo
                 '''
                 pass
-        """)
+        """
+        )
         reprec = testdir.inline_run(p, "--doctest-modules")
         reprec.assertoutcome(passed=1)
 
     def test_non_ignored_whitespace(self, testdir):
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
             doctest_optionflags = ELLIPSIS
-        """)
-        p = testdir.makepyfile("""
+        """
+        )
+        p = testdir.makepyfile(
+            """
             class MyClass(object):
                 '''
                 >>> a = "foo    "
                 >>> print(a)
                 foo
                 '''
                 pass
-        """)
+        """
+        )
         reprec = testdir.inline_run(p, "--doctest-modules")
         reprec.assertoutcome(failed=1, passed=0)
 
     def test_ignored_whitespace_glob(self, testdir):
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
             doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE
-        """)
-        p = testdir.maketxtfile(xdoc="""
+        """
+        )
+        p = testdir.maketxtfile(
+            xdoc="""
             >>> a = "foo    "
             >>> print(a)
             foo
-        """)
+        """
+        )
         reprec = testdir.inline_run(p, "--doctest-glob=x*.txt")
         reprec.assertoutcome(passed=1)
 
     def test_non_ignored_whitespace_glob(self, testdir):
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
             doctest_optionflags = ELLIPSIS
-        """)
-        p = testdir.maketxtfile(xdoc="""
+        """
+        )
+        p = testdir.maketxtfile(
+            xdoc="""
             >>> a = "foo    "
             >>> print(a)
             foo
-        """)
+        """
+        )
         reprec = testdir.inline_run(p, "--doctest-glob=x*.txt")
         reprec.assertoutcome(failed=1, passed=0)
 
     def test_contains_unicode(self, testdir):
         """Fix internal error with docstrings containing non-ascii characters.
         """
-        testdir.makepyfile(u'''
+        testdir.makepyfile(
+            u'''
             # encoding: utf-8
             def foo():
                 """
                 >>> name = 'с' # not letter 'c' but instead Cyrillic 's'.
                 'anything'
                 """
-        ''')
-        result = testdir.runpytest('--doctest-modules')
-        result.stdout.fnmatch_lines([
-            'Got nothing',
-            '* 1 failed in*',
-        ])
+        '''
+        )
+        result = testdir.runpytest("--doctest-modules")
+        result.stdout.fnmatch_lines(["Got nothing", "* 1 failed in*"])
 
     def test_ignore_import_errors_on_doctest(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import asdf
 
             def add_one(x):
                 '''
                 >>> add_one(1)
                 2
                 '''
                 return x + 1
-        """)
+        """
+        )
 
-        reprec = testdir.inline_run(p, "--doctest-modules",
-                                    "--doctest-ignore-import-errors")
+        reprec = testdir.inline_run(
+            p, "--doctest-modules", "--doctest-ignore-import-errors"
+        )
         reprec.assertoutcome(skipped=1, failed=1, passed=0)
 
     def test_junit_report_for_doctest(self, testdir):
         """
         #713: Fix --junit-xml option when used with --doctest-modules.
         """
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def foo():
                 '''
                 >>> 1 + 1
                 3
                 '''
                 pass
-        """)
-        reprec = testdir.inline_run(p, "--doctest-modules",
-                                    "--junit-xml=junit.xml")
+        """
+        )
+        reprec = testdir.inline_run(p, "--doctest-modules", "--junit-xml=junit.xml")
         reprec.assertoutcome(failed=1)
 
     def test_unicode_doctest(self, testdir):
         """
         Test case for issue 2434: DecodeError on Python 2 when doctest contains non-ascii
         characters.
         """
-        p = testdir.maketxtfile(test_unicode_doctest="""
+        p = testdir.maketxtfile(
+            test_unicode_doctest="""
             .. doctest::
 
                 >>> print(
                 ...    "Hi\\n\\nByé")
                 Hi
                 ...
                 Byé
                 >>> 1/0  # Byé
                 1
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            '*UNEXPECTED EXCEPTION: ZeroDivisionError*',
-            '*1 failed*',
-        ])
+        result.stdout.fnmatch_lines(
+            ["*UNEXPECTED EXCEPTION: ZeroDivisionError*", "*1 failed*"]
+        )
 
     def test_unicode_doctest_module(self, testdir):
         """
         Test case for issue 2434: DecodeError on Python 2 when doctest docstring
         contains non-ascii characters.
         """
-        p = testdir.makepyfile(test_unicode_doctest_module="""
+        p = testdir.makepyfile(
+            test_unicode_doctest_module="""
             # -*- encoding: utf-8 -*-
             from __future__ import unicode_literals
 
             def fix_bad_unicode(text):
                 '''
                     >>> print(fix_bad_unicode('único'))
                     único
                 '''
                 return "único"
-        """)
-        result = testdir.runpytest(p, '--doctest-modules')
-        result.stdout.fnmatch_lines(['* 1 passed *'])
+        """
+        )
+        result = testdir.runpytest(p, "--doctest-modules")
+        result.stdout.fnmatch_lines(["* 1 passed *"])
+
+    def test_print_unicode_value(self, testdir):
+        """
+        Test case for issue 3583: Printing Unicode in doctest under Python 2.7
+        doesn't work
+        """
+        p = testdir.maketxtfile(
+            test_print_unicode_value=r"""
+            Here is a doctest::
+
+                >>> print(u'\xE5\xE9\xEE\xF8\xFC')
+                åéîøü
+        """
+        )
+        result = testdir.runpytest(p)
+        result.stdout.fnmatch_lines(["* 1 passed *"])
 
     def test_reportinfo(self, testdir):
-        '''
+        """
         Test case to make sure that DoctestItem.reportinfo() returns lineno.
-        '''
-        p = testdir.makepyfile(test_reportinfo="""
+        """
+        p = testdir.makepyfile(
+            test_reportinfo="""
             def foo(x):
                 '''
                     >>> foo('a')
                     'b'
                 '''
                 return 'c'
-        """)
-        items, reprec = testdir.inline_genitems(p, '--doctest-modules')
+        """
+        )
+        items, reprec = testdir.inline_genitems(p, "--doctest-modules")
         reportinfo = items[0].reportinfo()
         assert reportinfo[1] == 1
 
     def test_valid_setup_py(self, testdir):
-        '''
+        """
         Test to make sure that pytest ignores valid setup.py files when ran
         with --doctest-modules
-        '''
-        p = testdir.makepyfile(setup="""
+        """
+        p = testdir.makepyfile(
+            setup="""
             from setuptools import setup, find_packages
             setup(name='sample',
                   version='0.0',
                   description='description',
                   packages=find_packages()
             )
-        """)
-        result = testdir.runpytest(p, '--doctest-modules')
-        result.stdout.fnmatch_lines(['*collected 0 items*'])
+        """
+        )
+        result = testdir.runpytest(p, "--doctest-modules")
+        result.stdout.fnmatch_lines(["*collected 0 items*"])
 
     def test_invalid_setup_py(self, testdir):
-        '''
+        """
         Test to make sure that pytest reads setup.py files that are not used
         for python packages when ran with --doctest-modules
-        '''
-        p = testdir.makepyfile(setup="""
+        """
+        p = testdir.makepyfile(
+            setup="""
             def test_foo():
                 return 'bar'
-        """)
-        result = testdir.runpytest(p, '--doctest-modules')
-        result.stdout.fnmatch_lines(['*collected 1 item*'])
+        """
+        )
+        result = testdir.runpytest(p, "--doctest-modules")
+        result.stdout.fnmatch_lines(["*collected 1 item*"])
 
 
 class TestLiterals(object):
 
-    @pytest.mark.parametrize('config_mode', ['ini', 'comment'])
+    @pytest.mark.parametrize("config_mode", ["ini", "comment"])
     def test_allow_unicode(self, testdir, config_mode):
         """Test that doctests which output unicode work in all python versions
         tested by pytest when the ALLOW_UNICODE option is used (either in
         the ini file or by an inline comment).
         """
-        if config_mode == 'ini':
-            testdir.makeini('''
+        if config_mode == "ini":
+            testdir.makeini(
+                """
             [pytest]
             doctest_optionflags = ALLOW_UNICODE
-            ''')
-            comment = ''
+            """
+            )
+            comment = ""
         else:
-            comment = '#doctest: +ALLOW_UNICODE'
+            comment = "#doctest: +ALLOW_UNICODE"
 
-        testdir.maketxtfile(test_doc="""
+        testdir.maketxtfile(
+            test_doc="""
             >>> b'12'.decode('ascii') {comment}
             '12'
-        """.format(comment=comment))
-        testdir.makepyfile(foo="""
+        """.format(
+                comment=comment
+            )
+        )
+        testdir.makepyfile(
+            foo="""
             def foo():
               '''
               >>> b'12'.decode('ascii') {comment}
               '12'
               '''
-        """.format(comment=comment))
+        """.format(
+                comment=comment
+            )
+        )
         reprec = testdir.inline_run("--doctest-modules")
         reprec.assertoutcome(passed=2)
 
-    @pytest.mark.parametrize('config_mode', ['ini', 'comment'])
+    @pytest.mark.parametrize("config_mode", ["ini", "comment"])
     def test_allow_bytes(self, testdir, config_mode):
         """Test that doctests which output bytes work in all python versions
         tested by pytest when the ALLOW_BYTES option is used (either in
         the ini file or by an inline comment)(#1287).
         """
-        if config_mode == 'ini':
-            testdir.makeini('''
+        if config_mode == "ini":
+            testdir.makeini(
+                """
             [pytest]
             doctest_optionflags = ALLOW_BYTES
-            ''')
-            comment = ''
+            """
+            )
+            comment = ""
         else:
-            comment = '#doctest: +ALLOW_BYTES'
+            comment = "#doctest: +ALLOW_BYTES"
 
-        testdir.maketxtfile(test_doc="""
+        testdir.maketxtfile(
+            test_doc="""
             >>> b'foo'  {comment}
             'foo'
-        """.format(comment=comment))
-        testdir.makepyfile(foo="""
+        """.format(
+                comment=comment
+            )
+        )
+        testdir.makepyfile(
+            foo="""
             def foo():
               '''
               >>> b'foo'  {comment}
               'foo'
               '''
-        """.format(comment=comment))
+        """.format(
+                comment=comment
+            )
+        )
         reprec = testdir.inline_run("--doctest-modules")
         reprec.assertoutcome(passed=2)
 
     def test_unicode_string(self, testdir):
         """Test that doctests which output unicode fail in Python 2 when
         the ALLOW_UNICODE option is not used. The same test should pass
         in Python 3.
         """
-        testdir.maketxtfile(test_doc="""
+        testdir.maketxtfile(
+            test_doc="""
             >>> b'12'.decode('ascii')
             '12'
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         passed = int(sys.version_info[0] >= 3)
         reprec.assertoutcome(passed=passed, failed=int(not passed))
 
     def test_bytes_literal(self, testdir):
         """Test that doctests which output bytes fail in Python 3 when
         the ALLOW_BYTES option is not used. The same test should pass
         in Python 2 (#1287).
         """
-        testdir.maketxtfile(test_doc="""
+        testdir.maketxtfile(
+            test_doc="""
             >>> b'foo'
             'foo'
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         passed = int(sys.version_info[0] == 2)
         reprec.assertoutcome(passed=passed, failed=int(not passed))
 
 
 class TestDoctestSkips(object):
     """
     If all examples in a doctest are skipped due to the SKIP option, then
     the tests should be SKIPPED rather than PASSED. (#957)
     """
 
-    @pytest.fixture(params=['text', 'module'])
+    @pytest.fixture(params=["text", "module"])
     def makedoctest(self, testdir, request):
+
         def makeit(doctest):
             mode = request.param
-            if mode == 'text':
+            if mode == "text":
                 testdir.maketxtfile(doctest)
             else:
-                assert mode == 'module'
+                assert mode == "module"
                 testdir.makepyfile('"""\n%s"""' % doctest)
 
         return makeit
 
     def test_one_skipped(self, testdir, makedoctest):
-        makedoctest("""
+        makedoctest(
+            """
             >>> 1 + 1  # doctest: +SKIP
             2
             >>> 2 + 2
             4
-        """)
+        """
+        )
         reprec = testdir.inline_run("--doctest-modules")
         reprec.assertoutcome(passed=1)
 
     def test_one_skipped_failed(self, testdir, makedoctest):
-        makedoctest("""
+        makedoctest(
+            """
             >>> 1 + 1  # doctest: +SKIP
             2
             >>> 2 + 2
             200
-        """)
+        """
+        )
         reprec = testdir.inline_run("--doctest-modules")
         reprec.assertoutcome(failed=1)
 
     def test_all_skipped(self, testdir, makedoctest):
-        makedoctest("""
+        makedoctest(
+            """
             >>> 1 + 1  # doctest: +SKIP
             2
             >>> 2 + 2  # doctest: +SKIP
             200
-        """)
+        """
+        )
         reprec = testdir.inline_run("--doctest-modules")
         reprec.assertoutcome(skipped=1)
 
     def test_vacuous_all_skipped(self, testdir, makedoctest):
-        makedoctest('')
+        makedoctest("")
         reprec = testdir.inline_run("--doctest-modules")
         reprec.assertoutcome(passed=0, skipped=0)
 
+    def test_continue_on_failure(self, testdir):
+        testdir.maketxtfile(
+            test_something="""
+            >>> i = 5
+            >>> def foo():
+            ...     raise ValueError('error1')
+            >>> foo()
+            >>> i
+            >>> i + 2
+            7
+            >>> i + 1
+        """
+        )
+        result = testdir.runpytest("--doctest-modules", "--doctest-continue-on-failure")
+        result.assert_outcomes(passed=0, failed=1)
+        # The lines that contains the failure are 4, 5, and 8.  The first one
+        # is a stack trace and the other two are mismatches.
+        result.stdout.fnmatch_lines(
+            ["*4: UnexpectedException*", "*5: DocTestFailure*", "*8: DocTestFailure*"]
+        )
+
 
 class TestDoctestAutoUseFixtures(object):
 
-    SCOPES = ['module', 'session', 'class', 'function']
+    SCOPES = ["module", "session", "class", "function"]
 
     def test_doctest_module_session_fixture(self, testdir):
         """Test that session fixtures are initialized for doctest modules (#768)
         """
         # session fixture which changes some global data, which will
         # be accessed by doctests in a module
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             import sys
 
             @pytest.yield_fixture(autouse=True, scope='session')
             def myfixture():
                 assert not hasattr(sys, 'pytest_session_data')
                 sys.pytest_session_data = 1
                 yield
                 del sys.pytest_session_data
-        """)
-        testdir.makepyfile(foo="""
+        """
+        )
+        testdir.makepyfile(
+            foo="""
             import sys
 
             def foo():
               '''
               >>> assert sys.pytest_session_data == 1
               '''
 
             def bar():
               '''
               >>> assert sys.pytest_session_data == 1
               '''
-        """)
+        """
+        )
         result = testdir.runpytest("--doctest-modules")
-        result.stdout.fnmatch_lines('*2 passed*')
+        result.stdout.fnmatch_lines("*2 passed*")
 
-    @pytest.mark.parametrize('scope', SCOPES)
-    @pytest.mark.parametrize('enable_doctest', [True, False])
+    @pytest.mark.parametrize("scope", SCOPES)
+    @pytest.mark.parametrize("enable_doctest", [True, False])
     def test_fixture_scopes(self, testdir, scope, enable_doctest):
         """Test that auto-use fixtures work properly with doctest modules.
         See #1057 and #1100.
         """
-        testdir.makeconftest('''
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture(autouse=True, scope="{scope}")
             def auto(request):
                 return 99
-        '''.format(scope=scope))
-        testdir.makepyfile(test_1='''
+        """.format(
+                scope=scope
+            )
+        )
+        testdir.makepyfile(
+            test_1='''
             def test_foo():
                 """
                 >>> getfixture('auto') + 1
                 100
                 """
             def test_bar():
                 assert 1
-        ''')
-        params = ('--doctest-modules',) if enable_doctest else ()
+        '''
+        )
+        params = ("--doctest-modules",) if enable_doctest else ()
         passes = 3 if enable_doctest else 2
         result = testdir.runpytest(*params)
-        result.stdout.fnmatch_lines(['*=== %d passed in *' % passes])
+        result.stdout.fnmatch_lines(["*=== %d passed in *" % passes])
 
-    @pytest.mark.parametrize('scope', SCOPES)
-    @pytest.mark.parametrize('autouse', [True, False])
-    @pytest.mark.parametrize('use_fixture_in_doctest', [True, False])
-    def test_fixture_module_doctest_scopes(self, testdir, scope, autouse,
-                                           use_fixture_in_doctest):
+    @pytest.mark.parametrize("scope", SCOPES)
+    @pytest.mark.parametrize("autouse", [True, False])
+    @pytest.mark.parametrize("use_fixture_in_doctest", [True, False])
+    def test_fixture_module_doctest_scopes(
+        self, testdir, scope, autouse, use_fixture_in_doctest
+    ):
         """Test that auto-use fixtures work properly with doctest files.
         See #1057 and #1100.
         """
-        testdir.makeconftest('''
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture(autouse={autouse}, scope="{scope}")
             def auto(request):
                 return 99
-        '''.format(scope=scope, autouse=autouse))
+        """.format(
+                scope=scope, autouse=autouse
+            )
+        )
         if use_fixture_in_doctest:
-            testdir.maketxtfile(test_doc="""
+            testdir.maketxtfile(
+                test_doc="""
                 >>> getfixture('auto')
                 99
-            """)
+            """
+            )
         else:
-            testdir.maketxtfile(test_doc="""
+            testdir.maketxtfile(
+                test_doc="""
                 >>> 1 + 1
                 2
-            """)
-        result = testdir.runpytest('--doctest-modules')
-        assert 'FAILURES' not in str(result.stdout.str())
-        result.stdout.fnmatch_lines(['*=== 1 passed in *'])
+            """
+            )
+        result = testdir.runpytest("--doctest-modules")
+        assert "FAILURES" not in str(result.stdout.str())
+        result.stdout.fnmatch_lines(["*=== 1 passed in *"])
 
-    @pytest.mark.parametrize('scope', SCOPES)
+    @pytest.mark.parametrize("scope", SCOPES)
     def test_auto_use_request_attributes(self, testdir, scope):
         """Check that all attributes of a request in an autouse fixture
         behave as expected when requested for a doctest item.
         """
-        testdir.makeconftest('''
+        testdir.makeconftest(
+            """
             import pytest
 
             @pytest.fixture(autouse=True, scope="{scope}")
             def auto(request):
                 if "{scope}" == 'module':
                     assert request.module is None
                 if "{scope}" == 'class':
                     assert request.cls is None
                 if "{scope}" == 'function':
                     assert request.function is None
                 return 99
-        '''.format(scope=scope))
-        testdir.maketxtfile(test_doc="""
+        """.format(
+                scope=scope
+            )
+        )
+        testdir.maketxtfile(
+            test_doc="""
             >>> 1 + 1
             2
-        """)
-        result = testdir.runpytest('--doctest-modules')
-        assert 'FAILURES' not in str(result.stdout.str())
-        result.stdout.fnmatch_lines(['*=== 1 passed in *'])
+        """
+        )
+        result = testdir.runpytest("--doctest-modules")
+        assert "FAILURES" not in str(result.stdout.str())
+        result.stdout.fnmatch_lines(["*=== 1 passed in *"])
 
 
 class TestDoctestNamespaceFixture(object):
 
-    SCOPES = ['module', 'session', 'class', 'function']
+    SCOPES = ["module", "session", "class", "function"]
 
-    @pytest.mark.parametrize('scope', SCOPES)
+    @pytest.mark.parametrize("scope", SCOPES)
     def test_namespace_doctestfile(self, testdir, scope):
         """
         Check that inserting something into the namespace works in a
         simple text file doctest
         """
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             import contextlib
 
             @pytest.fixture(autouse=True, scope="{scope}")
             def add_contextlib(doctest_namespace):
                 doctest_namespace['cl'] = contextlib
-        """.format(scope=scope))
-        p = testdir.maketxtfile("""
+        """.format(
+                scope=scope
+            )
+        )
+        p = testdir.maketxtfile(
+            """
             >>> print(cl.__name__)
             contextlib
-        """)
+        """
+        )
         reprec = testdir.inline_run(p)
         reprec.assertoutcome(passed=1)
 
-    @pytest.mark.parametrize('scope', SCOPES)
+    @pytest.mark.parametrize("scope", SCOPES)
     def test_namespace_pyfile(self, testdir, scope):
         """
         Check that inserting something into the namespace works in a
         simple Python file docstring doctest
         """
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             import contextlib
 
             @pytest.fixture(autouse=True, scope="{scope}")
             def add_contextlib(doctest_namespace):
                 doctest_namespace['cl'] = contextlib
-        """.format(scope=scope))
-        p = testdir.makepyfile("""
+        """.format(
+                scope=scope
+            )
+        )
+        p = testdir.makepyfile(
+            """
             def foo():
                 '''
                 >>> print(cl.__name__)
                 contextlib
                 '''
-        """)
+        """
+        )
         reprec = testdir.inline_run(p, "--doctest-modules")
         reprec.assertoutcome(passed=1)
 
 
 class TestDoctestReportingOption(object):
+
     def _run_doctest_report(self, testdir, format):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def foo():
                 '''
                 >>> foo()
                    a  b
                 0  1  4
                 1  2  4
                 2  3  6
                 '''
                 print('   a  b\\n'
                       '0  1  4\\n'
                       '1  2  5\\n'
                       '2  3  6')
-            """)
+            """
+        )
         return testdir.runpytest("--doctest-modules", "--doctest-report", format)
 
-    @pytest.mark.parametrize('format', ['udiff', 'UDIFF', 'uDiFf'])
+    @pytest.mark.parametrize("format", ["udiff", "UDIFF", "uDiFf"])
     def test_doctest_report_udiff(self, testdir, format):
         result = self._run_doctest_report(testdir, format)
-        result.stdout.fnmatch_lines([
-            '     0  1  4',
-            '    -1  2  4',
-            '    +1  2  5',
-            '     2  3  6',
-        ])
+        result.stdout.fnmatch_lines(
+            ["     0  1  4", "    -1  2  4", "    +1  2  5", "     2  3  6"]
+        )
 
     def test_doctest_report_cdiff(self, testdir):
-        result = self._run_doctest_report(testdir, 'cdiff')
-        result.stdout.fnmatch_lines([
-            '         a  b',
-            '      0  1  4',
-            '    ! 1  2  4',
-            '      2  3  6',
-            '    --- 1,4 ----',
-            '         a  b',
-            '      0  1  4',
-            '    ! 1  2  5',
-            '      2  3  6',
-        ])
+        result = self._run_doctest_report(testdir, "cdiff")
+        result.stdout.fnmatch_lines(
+            [
+                "         a  b",
+                "      0  1  4",
+                "    ! 1  2  4",
+                "      2  3  6",
+                "    --- 1,4 ----",
+                "         a  b",
+                "      0  1  4",
+                "    ! 1  2  5",
+                "      2  3  6",
+            ]
+        )
 
     def test_doctest_report_ndiff(self, testdir):
-        result = self._run_doctest_report(testdir, 'ndiff')
-        result.stdout.fnmatch_lines([
-            '         a  b',
-            '      0  1  4',
-            '    - 1  2  4',
-            '    ?       ^',
-            '    + 1  2  5',
-            '    ?       ^',
-            '      2  3  6',
-        ])
+        result = self._run_doctest_report(testdir, "ndiff")
+        result.stdout.fnmatch_lines(
+            [
+                "         a  b",
+                "      0  1  4",
+                "    - 1  2  4",
+                "    ?       ^",
+                "    + 1  2  5",
+                "    ?       ^",
+                "      2  3  6",
+            ]
+        )
 
-    @pytest.mark.parametrize('format', ['none', 'only_first_failure'])
+    @pytest.mark.parametrize("format", ["none", "only_first_failure"])
     def test_doctest_report_none_or_only_first_failure(self, testdir, format):
         result = self._run_doctest_report(testdir, format)
-        result.stdout.fnmatch_lines([
-            'Expected:',
-            '       a  b',
-            '    0  1  4',
-            '    1  2  4',
-            '    2  3  6',
-            'Got:',
-            '       a  b',
-            '    0  1  4',
-            '    1  2  5',
-            '    2  3  6',
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "Expected:",
+                "       a  b",
+                "    0  1  4",
+                "    1  2  4",
+                "    2  3  6",
+                "Got:",
+                "       a  b",
+                "    0  1  4",
+                "    1  2  5",
+                "    2  3  6",
+            ]
+        )
 
     def test_doctest_report_invalid(self, testdir):
-        result = self._run_doctest_report(testdir, 'obviously_invalid_format')
-        result.stderr.fnmatch_lines([
-            "*error: argument --doctest-report: invalid choice: 'obviously_invalid_format' (choose from*"
-        ])
+        result = self._run_doctest_report(testdir, "obviously_invalid_format")
+        result.stderr.fnmatch_lines(
+            [
+                "*error: argument --doctest-report: invalid choice: 'obviously_invalid_format' (choose from*"
+            ]
+        )
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_entry_points.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_entry_points.py
@@ -1,14 +1,14 @@
 from __future__ import absolute_import, division, print_function
 import pkg_resources
 
 import pytest
 
 
-@pytest.mark.parametrize("entrypoint", ['py.test', 'pytest'])
+@pytest.mark.parametrize("entrypoint", ["py.test", "pytest"])
 def test_entry_point_exist(entrypoint):
-    assert entrypoint in pkg_resources.get_entry_map('pytest')['console_scripts']
+    assert entrypoint in pkg_resources.get_entry_map("pytest")["console_scripts"]
 
 
 def test_pytest_entry_points_are_identical():
-    entryMap = pkg_resources.get_entry_map('pytest')['console_scripts']
-    assert entryMap['pytest'].module_name == entryMap['py.test'].module_name
+    entryMap = pkg_resources.get_entry_map("pytest")["console_scripts"]
+    assert entryMap["pytest"].module_name == entryMap["py.test"].module_name
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_helpconfig.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_helpconfig.py
@@ -2,76 +2,71 @@ from __future__ import absolute_import, 
 from _pytest.main import EXIT_NOTESTSCOLLECTED
 import pytest
 
 
 def test_version(testdir, pytestconfig):
     result = testdir.runpytest("--version")
     assert result.ret == 0
     # p = py.path.local(py.__file__).dirpath()
-    result.stderr.fnmatch_lines([
-        '*pytest*%s*imported from*' % (pytest.__version__, )
-    ])
+    result.stderr.fnmatch_lines(["*pytest*%s*imported from*" % (pytest.__version__,)])
     if pytestconfig.pluginmanager.list_plugin_distinfo():
-        result.stderr.fnmatch_lines([
-            "*setuptools registered plugins:",
-            "*at*",
-        ])
+        result.stderr.fnmatch_lines(["*setuptools registered plugins:", "*at*"])
 
 
 def test_help(testdir):
     result = testdir.runpytest("--help")
     assert result.ret == 0
-    result.stdout.fnmatch_lines("""
+    result.stdout.fnmatch_lines(
+        """
         *-v*verbose*
         *setup.cfg*
         *minversion*
         *to see*markers*pytest --markers*
         *to see*fixtures*pytest --fixtures*
-    """)
+    """
+    )
 
 
 def test_hookvalidation_unknown(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         def pytest_hello(xyz):
             pass
-    """)
+    """
+    )
     result = testdir.runpytest()
     assert result.ret != 0
-    result.stdout.fnmatch_lines([
-        '*unknown hook*pytest_hello*'
-    ])
+    result.stdout.fnmatch_lines(["*unknown hook*pytest_hello*"])
 
 
 def test_hookvalidation_optional(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         import pytest
         @pytest.hookimpl(optionalhook=True)
         def pytest_hello(xyz):
             pass
-    """)
+    """
+    )
     result = testdir.runpytest()
     assert result.ret == EXIT_NOTESTSCOLLECTED
 
 
 def test_traceconfig(testdir):
     result = testdir.runpytest("--traceconfig")
-    result.stdout.fnmatch_lines([
-        "*using*pytest*py*",
-        "*active plugins*",
-    ])
+    result.stdout.fnmatch_lines(["*using*pytest*py*", "*active plugins*"])
 
 
 def test_debug(testdir, monkeypatch):
     result = testdir.runpytest_subprocess("--debug")
     assert result.ret == EXIT_NOTESTSCOLLECTED
     p = testdir.tmpdir.join("pytestdebug.log")
     assert "pytest_sessionstart" in p.read()
 
 
 def test_PYTEST_DEBUG(testdir, monkeypatch):
     monkeypatch.setenv("PYTEST_DEBUG", "1")
     result = testdir.runpytest_subprocess()
     assert result.ret == EXIT_NOTESTSCOLLECTED
-    result.stderr.fnmatch_lines([
-        "*pytest_plugin_registered*",
-        "*manager*PluginManager*"
-    ])
+    result.stderr.fnmatch_lines(
+        ["*pytest_plugin_registered*", "*manager*PluginManager*"]
+    )
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_junitxml.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_junitxml.py
@@ -18,22 +18,23 @@ def runandparse(testdir, *args):
 def assert_attr(node, **kwargs):
     __tracebackhide__ = True
 
     def nodeval(node, name):
         anode = node.getAttributeNode(name)
         if anode is not None:
             return anode.value
 
-    expected = dict((name, str(value)) for name, value in kwargs.items())
-    on_node = dict((name, nodeval(node, name)) for name in expected)
+    expected = {name: str(value) for name, value in kwargs.items()}
+    on_node = {name: nodeval(node, name) for name in expected}
     assert on_node == expected
 
 
 class DomNode(object):
+
     def __init__(self, dom):
         self.__node = dom
 
     def __repr__(self):
         return self.__node.toxml()
 
     def find_first_by_tag(self, tag):
         return self.find_nth_by_tag(tag, 0)
@@ -75,758 +76,886 @@ class DomNode(object):
         return self.__node.tagName
 
     @property
     def next_siebling(self):
         return type(self)(self.__node.nextSibling)
 
 
 class TestPython(object):
+
     def test_summing_simple(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def test_pass():
                 pass
             def test_fail():
                 assert 0
             def test_skip():
                 pytest.skip("")
             @pytest.mark.xfail
             def test_xfail():
                 assert 0
             @pytest.mark.xfail
             def test_xpass():
                 assert 1
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         assert result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(name="pytest", errors=0, failures=1, skips=2, tests=5)
 
     def test_summing_simple_with_errors(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture
             def fixture():
                 raise Exception()
             def test_pass():
                 pass
             def test_fail():
                 assert 0
             def test_error(fixture):
                 pass
             @pytest.mark.xfail
             def test_xfail():
                 assert False
             @pytest.mark.xfail(strict=True)
             def test_xpass():
                 assert True
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         assert result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(name="pytest", errors=1, failures=2, skips=1, tests=5)
 
     def test_timing_function(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import time, pytest
             def setup_module():
                 time.sleep(0.01)
             def teardown_module():
                 time.sleep(0.01)
             def test_sleep():
                 time.sleep(0.01)
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         node = dom.find_first_by_tag("testsuite")
         tnode = node.find_first_by_tag("testcase")
         val = tnode["time"]
         assert round(float(val), 2) >= 0.03
 
     def test_setup_error(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def arg(request):
                 raise ValueError()
             def test_function(arg):
                 pass
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         assert result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(errors=1, tests=1)
         tnode = node.find_first_by_tag("testcase")
         tnode.assert_attr(
             file="test_setup_error.py",
             line="5",
             classname="test_setup_error",
-            name="test_function")
+            name="test_function",
+        )
         fnode = tnode.find_first_by_tag("error")
         fnode.assert_attr(message="test setup failure")
         assert "ValueError" in fnode.toxml()
 
     def test_teardown_error(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def arg():
                 yield
                 raise ValueError()
             def test_function(arg):
                 pass
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         assert result.ret
         node = dom.find_first_by_tag("testsuite")
         tnode = node.find_first_by_tag("testcase")
         tnode.assert_attr(
             file="test_teardown_error.py",
             line="6",
             classname="test_teardown_error",
-            name="test_function")
+            name="test_function",
+        )
         fnode = tnode.find_first_by_tag("error")
         fnode.assert_attr(message="test teardown failure")
         assert "ValueError" in fnode.toxml()
 
     def test_call_failure_teardown_error(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def arg():
                 yield
                 raise Exception("Teardown Exception")
             def test_function(arg):
                 raise Exception("Call Exception")
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         assert result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(errors=1, failures=1, tests=1)
         first, second = dom.find_by_tag("testcase")
         if not first or not second or first == second:
             assert 0
         fnode = first.find_first_by_tag("failure")
         fnode.assert_attr(message="Exception: Call Exception")
         snode = second.find_first_by_tag("error")
         snode.assert_attr(message="test teardown failure")
 
     def test_skip_contains_name_reason(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def test_skip():
                 pytest.skip("hello23")
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         assert result.ret == 0
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(skips=1)
         tnode = node.find_first_by_tag("testcase")
         tnode.assert_attr(
             file="test_skip_contains_name_reason.py",
             line="1",
             classname="test_skip_contains_name_reason",
-            name="test_skip")
+            name="test_skip",
+        )
         snode = tnode.find_first_by_tag("skipped")
-        snode.assert_attr(type="pytest.skip", message="hello23", )
+        snode.assert_attr(type="pytest.skip", message="hello23")
 
     def test_mark_skip_contains_name_reason(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.skip(reason="hello24")
             def test_skip():
                 assert True
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         assert result.ret == 0
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(skips=1)
         tnode = node.find_first_by_tag("testcase")
         tnode.assert_attr(
             file="test_mark_skip_contains_name_reason.py",
             line="1",
             classname="test_mark_skip_contains_name_reason",
-            name="test_skip")
+            name="test_skip",
+        )
         snode = tnode.find_first_by_tag("skipped")
-        snode.assert_attr(type="pytest.skip", message="hello24", )
+        snode.assert_attr(type="pytest.skip", message="hello24")
 
     def test_mark_skipif_contains_name_reason(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             GLOBAL_CONDITION = True
             @pytest.mark.skipif(GLOBAL_CONDITION, reason="hello25")
             def test_skip():
                 assert True
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         assert result.ret == 0
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(skips=1)
         tnode = node.find_first_by_tag("testcase")
         tnode.assert_attr(
             file="test_mark_skipif_contains_name_reason.py",
             line="2",
             classname="test_mark_skipif_contains_name_reason",
-            name="test_skip")
+            name="test_skip",
+        )
         snode = tnode.find_first_by_tag("skipped")
-        snode.assert_attr(type="pytest.skip", message="hello25", )
+        snode.assert_attr(type="pytest.skip", message="hello25")
 
     def test_mark_skip_doesnt_capture_output(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.skip(reason="foo")
             def test_skip():
                 print("bar!")
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         assert result.ret == 0
         node_xml = dom.find_first_by_tag("testsuite").toxml()
         assert "bar!" not in node_xml
 
     def test_classname_instance(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             class TestClass(object):
                 def test_method(self):
                     assert 0
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         assert result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(failures=1)
         tnode = node.find_first_by_tag("testcase")
         tnode.assert_attr(
             file="test_classname_instance.py",
             line="1",
             classname="test_classname_instance.TestClass",
-            name="test_method")
+            name="test_method",
+        )
 
     def test_classname_nested_dir(self, testdir):
         p = testdir.tmpdir.ensure("sub", "test_hello.py")
         p.write("def test_func(): 0/0")
         result, dom = runandparse(testdir)
         assert result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(failures=1)
         tnode = node.find_first_by_tag("testcase")
         tnode.assert_attr(
             file=os.path.join("sub", "test_hello.py"),
             line="0",
             classname="sub.test_hello",
-            name="test_func")
+            name="test_func",
+        )
 
     def test_internal_error(self, testdir):
         testdir.makeconftest("def pytest_runtest_protocol(): 0 / 0")
         testdir.makepyfile("def test_function(): pass")
         result, dom = runandparse(testdir)
         assert result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(errors=1, tests=1)
         tnode = node.find_first_by_tag("testcase")
         tnode.assert_attr(classname="pytest", name="internal")
         fnode = tnode.find_first_by_tag("error")
         fnode.assert_attr(message="internal error")
         assert "Division" in fnode.toxml()
 
-    def test_failure_function(self, testdir):
-        testdir.makepyfile("""
+    @pytest.mark.parametrize("junit_logging", ["no", "system-out", "system-err"])
+    def test_failure_function(self, testdir, junit_logging):
+        testdir.makepyfile(
+            """
+            import logging
             import sys
+
             def test_fail():
                 print ("hello-stdout")
                 sys.stderr.write("hello-stderr\\n")
+                logging.info('info msg')
+                logging.warning('warning msg')
                 raise ValueError(42)
-        """)
+        """
+        )
 
-        result, dom = runandparse(testdir)
+        result, dom = runandparse(testdir, "-o", "junit_logging=%s" % junit_logging)
         assert result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(failures=1, tests=1)
         tnode = node.find_first_by_tag("testcase")
         tnode.assert_attr(
             file="test_failure_function.py",
-            line="1",
+            line="3",
             classname="test_failure_function",
-            name="test_fail")
+            name="test_fail",
+        )
         fnode = tnode.find_first_by_tag("failure")
         fnode.assert_attr(message="ValueError: 42")
         assert "ValueError" in fnode.toxml()
         systemout = fnode.next_siebling
         assert systemout.tag == "system-out"
         assert "hello-stdout" in systemout.toxml()
+        assert "info msg" not in systemout.toxml()
         systemerr = systemout.next_siebling
         assert systemerr.tag == "system-err"
         assert "hello-stderr" in systemerr.toxml()
+        assert "info msg" not in systemerr.toxml()
+
+        if junit_logging == "system-out":
+            assert "warning msg" in systemout.toxml()
+            assert "warning msg" not in systemerr.toxml()
+        elif junit_logging == "system-err":
+            assert "warning msg" not in systemout.toxml()
+            assert "warning msg" in systemerr.toxml()
+        elif junit_logging == "no":
+            assert "warning msg" not in systemout.toxml()
+            assert "warning msg" not in systemerr.toxml()
 
     def test_failure_verbose_message(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import sys
             def test_fail():
                 assert 0, "An error"
-        """)
+        """
+        )
 
         result, dom = runandparse(testdir)
         node = dom.find_first_by_tag("testsuite")
         tnode = node.find_first_by_tag("testcase")
         fnode = tnode.find_first_by_tag("failure")
         fnode.assert_attr(message="AssertionError: An error assert 0")
 
     def test_failure_escape(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.parametrize('arg1', "<&'", ids="<&'")
             def test_func(arg1):
                 print(arg1)
                 assert 0
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         assert result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(failures=3, tests=3)
 
         for index, char in enumerate("<&'"):
 
             tnode = node.find_nth_by_tag("testcase", index)
             tnode.assert_attr(
                 file="test_failure_escape.py",
                 line="1",
                 classname="test_failure_escape",
-                name="test_func[%s]" % char)
-            sysout = tnode.find_first_by_tag('system-out')
+                name="test_func[%s]" % char,
+            )
+            sysout = tnode.find_first_by_tag("system-out")
             text = sysout.text
-            assert text == '%s\n' % char
+            assert text == "%s\n" % char
 
     def test_junit_prefixing(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_func():
                 assert 0
             class TestHello(object):
                 def test_hello(self):
                     pass
-        """)
+        """
+        )
         result, dom = runandparse(testdir, "--junitprefix=xyz")
         assert result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(failures=1, tests=2)
         tnode = node.find_first_by_tag("testcase")
         tnode.assert_attr(
             file="test_junit_prefixing.py",
             line="0",
             classname="xyz.test_junit_prefixing",
-            name="test_func")
+            name="test_func",
+        )
         tnode = node.find_nth_by_tag("testcase", 1)
         tnode.assert_attr(
             file="test_junit_prefixing.py",
             line="3",
-            classname="xyz.test_junit_prefixing."
-            "TestHello",
-            name="test_hello")
+            classname="xyz.test_junit_prefixing." "TestHello",
+            name="test_hello",
+        )
 
     def test_xfailure_function(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def test_xfail():
                 pytest.xfail("42")
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         assert not result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(skips=1, tests=1)
         tnode = node.find_first_by_tag("testcase")
         tnode.assert_attr(
             file="test_xfailure_function.py",
             line="1",
             classname="test_xfailure_function",
-            name="test_xfail")
+            name="test_xfail",
+        )
         fnode = tnode.find_first_by_tag("skipped")
         fnode.assert_attr(message="expected test failure")
         # assert "ValueError" in fnode.toxml()
 
+    def test_xfail_captures_output_once(self, testdir):
+        testdir.makepyfile(
+            """
+            import sys
+            import pytest
+
+            @pytest.mark.xfail()
+            def test_fail():
+                sys.stdout.write('XFAIL This is stdout')
+                sys.stderr.write('XFAIL This is stderr')
+                assert 0
+        """
+        )
+        result, dom = runandparse(testdir)
+        node = dom.find_first_by_tag("testsuite")
+        tnode = node.find_first_by_tag("testcase")
+        assert len(tnode.find_by_tag("system-err")) == 1
+        assert len(tnode.find_by_tag("system-out")) == 1
+
     def test_xfailure_xpass(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.xfail
             def test_xpass():
                 pass
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         # assert result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(skips=0, tests=1)
         tnode = node.find_first_by_tag("testcase")
         tnode.assert_attr(
             file="test_xfailure_xpass.py",
             line="1",
             classname="test_xfailure_xpass",
-            name="test_xpass")
+            name="test_xpass",
+        )
 
     def test_xfailure_xpass_strict(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.xfail(strict=True, reason="This needs to fail!")
             def test_xpass():
                 pass
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         # assert result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(skips=0, tests=1)
         tnode = node.find_first_by_tag("testcase")
         tnode.assert_attr(
             file="test_xfailure_xpass_strict.py",
             line="1",
             classname="test_xfailure_xpass_strict",
-            name="test_xpass")
+            name="test_xpass",
+        )
         fnode = tnode.find_first_by_tag("failure")
         fnode.assert_attr(message="[XPASS(strict)] This needs to fail!")
 
     def test_collect_error(self, testdir):
         testdir.makepyfile("syntax error")
         result, dom = runandparse(testdir)
         assert result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(errors=1, tests=1)
         tnode = node.find_first_by_tag("testcase")
-        tnode.assert_attr(
-            file="test_collect_error.py",
-            name="test_collect_error")
+        tnode.assert_attr(file="test_collect_error.py", name="test_collect_error")
         assert tnode["line"] is None
         fnode = tnode.find_first_by_tag("error")
         fnode.assert_attr(message="collection failure")
         assert "SyntaxError" in fnode.toxml()
 
     def test_unicode(self, testdir):
-        value = 'hx\xc4\x85\xc4\x87\n'
-        testdir.makepyfile("""
+        value = "hx\xc4\x85\xc4\x87\n"
+        testdir.makepyfile(
+            """
             # coding: latin1
             def test_hello():
                 print (%r)
                 assert 0
-        """ % value)
+        """
+            % value
+        )
         result, dom = runandparse(testdir)
         assert result.ret == 1
         tnode = dom.find_first_by_tag("testcase")
         fnode = tnode.find_first_by_tag("failure")
         if not sys.platform.startswith("java"):
             assert "hx" in fnode.toxml()
 
     def test_assertion_binchars(self, testdir):
         """this test did fail when the escaping wasnt strict"""
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
 
             M1 = '\x01\x02\x03\x04'
             M2 = '\x01\x02\x03\x05'
 
             def test_str_compare():
                 assert M1 == M2
-            """)
+            """
+        )
         result, dom = runandparse(testdir)
         print(dom.toxml())
 
     def test_pass_captures_stdout(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_pass():
                 print('hello-stdout')
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         node = dom.find_first_by_tag("testsuite")
         pnode = node.find_first_by_tag("testcase")
         systemout = pnode.find_first_by_tag("system-out")
         assert "hello-stdout" in systemout.toxml()
 
     def test_pass_captures_stderr(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import sys
             def test_pass():
                 sys.stderr.write('hello-stderr')
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         node = dom.find_first_by_tag("testsuite")
         pnode = node.find_first_by_tag("testcase")
         systemout = pnode.find_first_by_tag("system-err")
         assert "hello-stderr" in systemout.toxml()
 
     def test_setup_error_captures_stdout(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             @pytest.fixture
             def arg(request):
                 print('hello-stdout')
                 raise ValueError()
             def test_function(arg):
                 pass
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         node = dom.find_first_by_tag("testsuite")
         pnode = node.find_first_by_tag("testcase")
         systemout = pnode.find_first_by_tag("system-out")
         assert "hello-stdout" in systemout.toxml()
 
     def test_setup_error_captures_stderr(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import sys
             import pytest
 
             @pytest.fixture
             def arg(request):
                 sys.stderr.write('hello-stderr')
                 raise ValueError()
             def test_function(arg):
                 pass
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         node = dom.find_first_by_tag("testsuite")
         pnode = node.find_first_by_tag("testcase")
         systemout = pnode.find_first_by_tag("system-err")
         assert "hello-stderr" in systemout.toxml()
 
     def test_avoid_double_stdout(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import sys
             import pytest
 
             @pytest.fixture
             def arg(request):
                 yield
                 sys.stdout.write('hello-stdout teardown')
                 raise ValueError()
             def test_function(arg):
                 sys.stdout.write('hello-stdout call')
-        """)
+        """
+        )
         result, dom = runandparse(testdir)
         node = dom.find_first_by_tag("testsuite")
         pnode = node.find_first_by_tag("testcase")
         systemout = pnode.find_first_by_tag("system-out")
         assert "hello-stdout call" in systemout.toxml()
         assert "hello-stdout teardown" in systemout.toxml()
 
 
 def test_mangle_test_address():
     from _pytest.junitxml import mangle_test_address
-    address = '::'.join(
-        ["a/my.py.thing.py", "Class", "()", "method", "[a-1-::]"])
+
+    address = "::".join(["a/my.py.thing.py", "Class", "()", "method", "[a-1-::]"])
     newnames = mangle_test_address(address)
     assert newnames == ["a.my.py.thing", "Class", "method", "[a-1-::]"]
 
 
 def test_dont_configure_on_slaves(tmpdir):
     gotten = []
 
     class FakeConfig(object):
+
         def __init__(self):
             self.pluginmanager = self
             self.option = self
 
         def getini(self, name):
             return "pytest"
 
         junitprefix = None
         # XXX: shouldnt need tmpdir ?
-        xmlpath = str(tmpdir.join('junix.xml'))
+        xmlpath = str(tmpdir.join("junix.xml"))
         register = gotten.append
 
     fake_config = FakeConfig()
     from _pytest import junitxml
+
     junitxml.pytest_configure(fake_config)
     assert len(gotten) == 1
     FakeConfig.slaveinput = None
     junitxml.pytest_configure(fake_config)
     assert len(gotten) == 1
 
 
 class TestNonPython(object):
+
     def test_summing_simple(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             def pytest_collect_file(path, parent):
                 if path.ext == ".xyz":
                     return MyItem(path, parent)
             class MyItem(pytest.Item):
                 def __init__(self, path, parent):
                     super(MyItem, self).__init__(path.basename, parent)
                     self.fspath = path
                 def runtest(self):
                     raise ValueError(42)
                 def repr_failure(self, excinfo):
                     return "custom item runtest failed"
-        """)
+        """
+        )
         testdir.tmpdir.join("myfile.xyz").write("hello")
         result, dom = runandparse(testdir)
         assert result.ret
         node = dom.find_first_by_tag("testsuite")
         node.assert_attr(errors=0, failures=1, skips=0, tests=1)
         tnode = node.find_first_by_tag("testcase")
         tnode.assert_attr(name="myfile.xyz")
         fnode = tnode.find_first_by_tag("failure")
         fnode.assert_attr(message="custom item runtest failed")
         assert "custom item runtest failed" in fnode.toxml()
 
 
 def test_nullbyte(testdir):
     # A null byte can not occur in XML (see section 2.2 of the spec)
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import sys
         def test_print_nullbyte():
             sys.stdout.write('Here the null -->' + chr(0) + '<--')
             sys.stdout.write('In repr form -->' + repr(chr(0)) + '<--')
             assert False
-    """)
-    xmlf = testdir.tmpdir.join('junit.xml')
-    testdir.runpytest('--junitxml=%s' % xmlf)
+    """
+    )
+    xmlf = testdir.tmpdir.join("junit.xml")
+    testdir.runpytest("--junitxml=%s" % xmlf)
     text = xmlf.read()
-    assert '\x00' not in text
-    assert '#x00' in text
+    assert "\x00" not in text
+    assert "#x00" in text
 
 
 def test_nullbyte_replace(testdir):
     # Check if the null byte gets replaced
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import sys
         def test_print_nullbyte():
             sys.stdout.write('Here the null -->' + chr(0) + '<--')
             sys.stdout.write('In repr form -->' + repr(chr(0)) + '<--')
             assert False
-    """)
-    xmlf = testdir.tmpdir.join('junit.xml')
-    testdir.runpytest('--junitxml=%s' % xmlf)
+    """
+    )
+    xmlf = testdir.tmpdir.join("junit.xml")
+    testdir.runpytest("--junitxml=%s" % xmlf)
     text = xmlf.read()
-    assert '#x0' in text
+    assert "#x0" in text
 
 
 def test_invalid_xml_escape():
     # Test some more invalid xml chars, the full range should be
     # tested really but let's just thest the edges of the ranges
     # intead.
     # XXX This only tests low unicode character points for now as
     #     there are some issues with the testing infrastructure for
     #     the higher ones.
     # XXX Testing 0xD (\r) is tricky as it overwrites the just written
     #     line in the output, so we skip it too.
     global unichr
     try:
         unichr(65)
     except NameError:
         unichr = chr
-    invalid = (0x00, 0x1, 0xB, 0xC, 0xE, 0x19, 27,  # issue #126
-               0xD800, 0xDFFF, 0xFFFE, 0x0FFFF)  # , 0x110000)
-    valid = (0x9, 0xA, 0x20, )
+    invalid = (
+        0x00,
+        0x1,
+        0xB,
+        0xC,
+        0xE,
+        0x19,
+        27,  # issue #126
+        0xD800,
+        0xDFFF,
+        0xFFFE,
+        0x0FFFF,
+    )  # , 0x110000)
+    valid = (0x9, 0xA, 0x20)
     # 0xD, 0xD7FF, 0xE000, 0xFFFD, 0x10000, 0x10FFFF)
 
     from _pytest.junitxml import bin_xml_escape
 
     for i in invalid:
         got = bin_xml_escape(unichr(i)).uniobj
         if i <= 0xFF:
-            expected = '#x%02X' % i
+            expected = "#x%02X" % i
         else:
-            expected = '#x%04X' % i
+            expected = "#x%04X" % i
         assert got == expected
     for i in valid:
         assert chr(i) == bin_xml_escape(unichr(i)).uniobj
 
 
 def test_logxml_path_expansion(tmpdir, monkeypatch):
-    home_tilde = py.path.local(os.path.expanduser('~')).join('test.xml')
+    home_tilde = py.path.local(os.path.expanduser("~")).join("test.xml")
 
-    xml_tilde = LogXML('~%stest.xml' % tmpdir.sep, None)
+    xml_tilde = LogXML("~%stest.xml" % tmpdir.sep, None)
     assert xml_tilde.logfile == home_tilde
 
     # this is here for when $HOME is not set correct
     monkeypatch.setenv("HOME", tmpdir)
-    home_var = os.path.normpath(os.path.expandvars('$HOME/test.xml'))
+    home_var = os.path.normpath(os.path.expandvars("$HOME/test.xml"))
 
-    xml_var = LogXML('$HOME%stest.xml' % tmpdir.sep, None)
+    xml_var = LogXML("$HOME%stest.xml" % tmpdir.sep, None)
     assert xml_var.logfile == home_var
 
 
 def test_logxml_changingdir(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_func():
             import os
             os.chdir("a")
-    """)
+    """
+    )
     testdir.tmpdir.mkdir("a")
     result = testdir.runpytest("--junitxml=a/x.xml")
     assert result.ret == 0
     assert testdir.tmpdir.join("a/x.xml").check()
 
 
 def test_logxml_makedir(testdir):
     """--junitxml should automatically create directories for the xml file"""
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_pass():
             pass
-    """)
+    """
+    )
     result = testdir.runpytest("--junitxml=path/to/results.xml")
     assert result.ret == 0
     assert testdir.tmpdir.join("path/to/results.xml").check()
 
 
 def test_logxml_check_isdir(testdir):
     """Give an error if --junit-xml is a directory (#2089)"""
     result = testdir.runpytest("--junit-xml=.")
     result.stderr.fnmatch_lines(["*--junitxml must be a filename*"])
 
 
 def test_escaped_parametrized_names_xml(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         @pytest.mark.parametrize('char', [u"\\x00"])
         def test_func(char):
             assert char
-    """)
+    """
+    )
     result, dom = runandparse(testdir)
     assert result.ret == 0
     node = dom.find_first_by_tag("testcase")
     node.assert_attr(name="test_func[\\x00]")
 
 
 def test_double_colon_split_function_issue469(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         @pytest.mark.parametrize('param', ["double::colon"])
         def test_func(param):
             pass
-    """)
+    """
+    )
     result, dom = runandparse(testdir)
     assert result.ret == 0
     node = dom.find_first_by_tag("testcase")
     node.assert_attr(classname="test_double_colon_split_function_issue469")
-    node.assert_attr(name='test_func[double::colon]')
+    node.assert_attr(name="test_func[double::colon]")
 
 
 def test_double_colon_split_method_issue469(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         class TestClass(object):
             @pytest.mark.parametrize('param', ["double::colon"])
             def test_func(self, param):
                 pass
-    """)
+    """
+    )
     result, dom = runandparse(testdir)
     assert result.ret == 0
     node = dom.find_first_by_tag("testcase")
-    node.assert_attr(
-        classname="test_double_colon_split_method_issue469.TestClass")
-    node.assert_attr(name='test_func[double::colon]')
+    node.assert_attr(classname="test_double_colon_split_method_issue469.TestClass")
+    node.assert_attr(name="test_func[double::colon]")
 
 
 def test_unicode_issue368(testdir):
     path = testdir.tmpdir.join("test.xml")
     log = LogXML(str(path), None)
     ustr = py.builtin._totext("ВНИ!", "utf-8")
     from _pytest.runner import BaseReport
 
     class Report(BaseReport):
         longrepr = ustr
         sections = []
         nodeid = "something"
-        location = 'tests/filename.py', 42, 'TestClass.method'
+        location = "tests/filename.py", 42, "TestClass.method"
 
     test_report = Report()
 
     # hopefully this is not too brittle ...
     log.pytest_sessionstart()
     node_reporter = log._opentestcase(test_report)
     node_reporter.append_failure(test_report)
     node_reporter.append_collect_error(test_report)
@@ -837,106 +966,133 @@ def test_unicode_issue368(testdir):
     test_report.longrepr = "filename", 1, "Skipped: 卡嘣嘣"
     node_reporter.append_skipped(test_report)
     test_report.wasxfail = ustr
     node_reporter.append_skipped(test_report)
     log.pytest_sessionfinish()
 
 
 def test_record_property(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
 
         @pytest.fixture
-        def other(record_xml_property):
-            record_xml_property("bar", 1)
-        def test_record(record_xml_property, other):
-            record_xml_property("foo", "<1");
-    """)
-    result, dom = runandparse(testdir, '-rw')
+        def other(record_property):
+            record_property("bar", 1)
+        def test_record(record_property, other):
+            record_property("foo", "<1");
+    """
+    )
+    result, dom = runandparse(testdir, "-rwv")
     node = dom.find_first_by_tag("testsuite")
     tnode = node.find_first_by_tag("testcase")
-    psnode = tnode.find_first_by_tag('properties')
-    pnodes = psnode.find_by_tag('property')
+    psnode = tnode.find_first_by_tag("properties")
+    pnodes = psnode.find_by_tag("property")
     pnodes[0].assert_attr(name="bar", value="1")
     pnodes[1].assert_attr(name="foo", value="<1")
-    result.stdout.fnmatch_lines([
-        'test_record_property.py::test_record',
-        '*record_xml_property*experimental*',
-    ])
 
 
 def test_record_property_same_name(testdir):
-    testdir.makepyfile("""
-        def test_record_with_same_name(record_xml_property):
-            record_xml_property("foo", "bar")
-            record_xml_property("foo", "baz")
-    """)
-    result, dom = runandparse(testdir, '-rw')
+    testdir.makepyfile(
+        """
+        def test_record_with_same_name(record_property):
+            record_property("foo", "bar")
+            record_property("foo", "baz")
+    """
+    )
+    result, dom = runandparse(testdir, "-rw")
     node = dom.find_first_by_tag("testsuite")
     tnode = node.find_first_by_tag("testcase")
-    psnode = tnode.find_first_by_tag('properties')
-    pnodes = psnode.find_by_tag('property')
+    psnode = tnode.find_first_by_tag("properties")
+    pnodes = psnode.find_by_tag("property")
     pnodes[0].assert_attr(name="foo", value="bar")
     pnodes[1].assert_attr(name="foo", value="baz")
 
 
+def test_record_attribute(testdir):
+    testdir.makepyfile(
+        """
+        import pytest
+
+        @pytest.fixture
+        def other(record_xml_attribute):
+            record_xml_attribute("bar", 1)
+        def test_record(record_xml_attribute, other):
+            record_xml_attribute("foo", "<1");
+    """
+    )
+    result, dom = runandparse(testdir, "-rw")
+    node = dom.find_first_by_tag("testsuite")
+    tnode = node.find_first_by_tag("testcase")
+    tnode.assert_attr(bar="1")
+    tnode.assert_attr(foo="<1")
+    result.stdout.fnmatch_lines(
+        ["test_record_attribute.py::test_record", "*record_xml_attribute*experimental*"]
+    )
+
+
 def test_random_report_log_xdist(testdir):
     """xdist calls pytest_runtest_logreport as they are executed by the slaves,
     with nodes from several nodes overlapping, so junitxml must cope with that
     to produce correct reports. #1064
     """
-    pytest.importorskip('xdist')
-    testdir.makepyfile("""
+    pytest.importorskip("xdist")
+    testdir.makepyfile(
+        """
         import pytest, time
         @pytest.mark.parametrize('i', list(range(30)))
         def test_x(i):
             assert i != 22
-    """)
-    _, dom = runandparse(testdir, '-n2')
+    """
+    )
+    _, dom = runandparse(testdir, "-n2")
     suite_node = dom.find_first_by_tag("testsuite")
     failed = []
     for case_node in suite_node.find_by_tag("testcase"):
-        if case_node.find_first_by_tag('failure'):
-            failed.append(case_node['name'])
+        if case_node.find_first_by_tag("failure"):
+            failed.append(case_node["name"])
 
-    assert failed == ['test_x[22]']
+    assert failed == ["test_x[22]"]
 
 
 def test_runs_twice(testdir):
-    f = testdir.makepyfile('''
+    f = testdir.makepyfile(
+        """
         def test_pass():
             pass
-    ''')
+    """
+    )
 
     result, dom = runandparse(testdir, f, f)
-    assert 'INTERNALERROR' not in result.stdout.str()
-    first, second = [x['classname'] for x in dom.find_by_tag("testcase")]
+    assert "INTERNALERROR" not in result.stdout.str()
+    first, second = [x["classname"] for x in dom.find_by_tag("testcase")]
     assert first == second
 
 
-@pytest.mark.xfail(reason='hangs', run=False)
+@pytest.mark.xfail(reason="hangs", run=False)
 def test_runs_twice_xdist(testdir):
-    pytest.importorskip('xdist')
-    f = testdir.makepyfile('''
+    pytest.importorskip("xdist")
+    f = testdir.makepyfile(
+        """
         def test_pass():
             pass
-    ''')
+    """
+    )
 
-    result, dom = runandparse(
-        testdir, f,
-        '--dist', 'each', '--tx', '2*popen',)
-    assert 'INTERNALERROR' not in result.stdout.str()
-    first, second = [x['classname'] for x in dom.find_by_tag("testcase")]
+    result, dom = runandparse(testdir, f, "--dist", "each", "--tx", "2*popen")
+    assert "INTERNALERROR" not in result.stdout.str()
+    first, second = [x["classname"] for x in dom.find_by_tag("testcase")]
     assert first == second
 
 
 def test_fancy_items_regression(testdir):
     # issue 1259
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         import pytest
         class FunItem(pytest.Item):
             def runtest(self):
                 pass
         class NoFunItem(pytest.Item):
             def runtest(self):
                 pass
 
@@ -946,117 +1102,130 @@ def test_fancy_items_regression(testdir)
                     FunItem('a', self),
                     NoFunItem('a', self),
                     NoFunItem('b', self),
                 ]
 
         def pytest_collect_file(path, parent):
             if path.check(ext='.py'):
                 return FunCollector(path, parent)
-    """)
+    """
+    )
 
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         def test_pass():
             pass
-    ''')
+    """
+    )
 
     result, dom = runandparse(testdir)
 
-    assert 'INTERNALERROR' not in result.stdout.str()
+    assert "INTERNALERROR" not in result.stdout.str()
 
     items = sorted(
-        '%(classname)s %(name)s %(file)s' % x
+        "%(classname)s %(name)s %(file)s" % x for x in dom.find_by_tag("testcase")
+    )
+    import pprint
 
-        for x in dom.find_by_tag("testcase"))
-    import pprint
     pprint.pprint(items)
-    assert items == [
-        u'conftest a conftest.py',
-        u'conftest a conftest.py',
-        u'conftest b conftest.py',
-        u'test_fancy_items_regression a test_fancy_items_regression.py',
-        u'test_fancy_items_regression a test_fancy_items_regression.py',
-        u'test_fancy_items_regression b test_fancy_items_regression.py',
-        u'test_fancy_items_regression test_pass'
-        u' test_fancy_items_regression.py',
-    ]
+    assert (
+        items
+        == [
+            u"conftest a conftest.py",
+            u"conftest a conftest.py",
+            u"conftest b conftest.py",
+            u"test_fancy_items_regression a test_fancy_items_regression.py",
+            u"test_fancy_items_regression a test_fancy_items_regression.py",
+            u"test_fancy_items_regression b test_fancy_items_regression.py",
+            u"test_fancy_items_regression test_pass" u" test_fancy_items_regression.py",
+        ]
+    )
 
 
 def test_global_properties(testdir):
     path = testdir.tmpdir.join("test_global_properties.xml")
     log = LogXML(str(path), None)
     from _pytest.runner import BaseReport
 
     class Report(BaseReport):
         sections = []
         nodeid = "test_node_id"
 
     log.pytest_sessionstart()
-    log.add_global_property('foo', 1)
-    log.add_global_property('bar', 2)
+    log.add_global_property("foo", 1)
+    log.add_global_property("bar", 2)
     log.pytest_sessionfinish()
 
     dom = minidom.parse(str(path))
 
-    properties = dom.getElementsByTagName('properties')
+    properties = dom.getElementsByTagName("properties")
 
-    assert (properties.length == 1), "There must be one <properties> node"
+    assert properties.length == 1, "There must be one <properties> node"
 
-    property_list = dom.getElementsByTagName('property')
+    property_list = dom.getElementsByTagName("property")
 
-    assert (property_list.length == 2), "There most be only 2 property nodes"
+    assert property_list.length == 2, "There most be only 2 property nodes"
 
-    expected = {'foo': '1', 'bar': '2'}
+    expected = {"foo": "1", "bar": "2"}
     actual = {}
 
     for p in property_list:
-        k = str(p.getAttribute('name'))
-        v = str(p.getAttribute('value'))
+        k = str(p.getAttribute("name"))
+        v = str(p.getAttribute("value"))
         actual[k] = v
 
     assert actual == expected
 
 
 def test_url_property(testdir):
     test_url = "http://www.github.com/pytest-dev"
     path = testdir.tmpdir.join("test_url_property.xml")
     log = LogXML(str(path), None)
     from _pytest.runner import BaseReport
 
     class Report(BaseReport):
         longrepr = "FooBarBaz"
         sections = []
         nodeid = "something"
-        location = 'tests/filename.py', 42, 'TestClass.method'
+        location = "tests/filename.py", 42, "TestClass.method"
         url = test_url
 
     test_report = Report()
 
     log.pytest_sessionstart()
     node_reporter = log._opentestcase(test_report)
     node_reporter.append_failure(test_report)
     log.pytest_sessionfinish()
 
-    test_case = minidom.parse(str(path)).getElementsByTagName('testcase')[0]
+    test_case = minidom.parse(str(path)).getElementsByTagName("testcase")[0]
 
-    assert (test_case.getAttribute('url') == test_url), "The URL did not get written to the xml"
+    assert (
+        test_case.getAttribute("url") == test_url
+    ), "The URL did not get written to the xml"
 
 
-@pytest.mark.parametrize('suite_name', ['my_suite', ''])
+@pytest.mark.parametrize("suite_name", ["my_suite", ""])
 def test_set_suite_name(testdir, suite_name):
     if suite_name:
-        testdir.makeini("""
+        testdir.makeini(
+            """
             [pytest]
-            junit_suite_name={0}
-        """.format(suite_name))
+            junit_suite_name={}
+        """.format(
+                suite_name
+            )
+        )
         expected = suite_name
     else:
-        expected = 'pytest'
-    testdir.makepyfile("""
+        expected = "pytest"
+    testdir.makepyfile(
+        """
         import pytest
 
         def test_func():
             pass
-    """)
+    """
+    )
     result, dom = runandparse(testdir)
     assert result.ret == 0
     node = dom.find_first_by_tag("testsuite")
     node.assert_attr(name=expected)
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_mark.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_mark.py
@@ -1,850 +1,1037 @@
 from __future__ import absolute_import, division, print_function
 import os
 import sys
-
+import mock
 import pytest
-from _pytest.mark import MarkGenerator as Mark, ParameterSet, transfer_markers
+from _pytest.mark import (
+    MarkGenerator as Mark,
+    ParameterSet,
+    transfer_markers,
+    EMPTY_PARAMETERSET_OPTION,
+)
+from _pytest.nodes import Node
+
+ignore_markinfo = pytest.mark.filterwarnings(
+    "ignore:MarkInfo objects:_pytest.deprecated.RemovedInPytest4Warning"
+)
 
 
 class TestMark(object):
+
     def test_markinfo_repr(self):
         from _pytest.mark import MarkInfo, Mark
-        m = MarkInfo(Mark("hello", (1, 2), {}))
+
+        m = MarkInfo.for_mark(Mark("hello", (1, 2), {}))
         repr(m)
 
-    @pytest.mark.parametrize('attr', ['mark', 'param'])
-    @pytest.mark.parametrize('modulename', ['py.test', 'pytest'])
+    @pytest.mark.parametrize("attr", ["mark", "param"])
+    @pytest.mark.parametrize("modulename", ["py.test", "pytest"])
     def test_pytest_exists_in_namespace_all(self, attr, modulename):
         module = sys.modules[modulename]
         assert attr in module.__all__
 
     def test_pytest_mark_notcallable(self):
         mark = Mark()
         pytest.raises((AttributeError, TypeError), mark)
 
     def test_mark_with_param(self):
+
         def some_function(abc):
             pass
 
         class SomeClass(object):
             pass
 
         assert pytest.mark.fun(some_function) is some_function
         assert pytest.mark.fun.with_args(some_function) is not some_function
 
         assert pytest.mark.fun(SomeClass) is SomeClass
         assert pytest.mark.fun.with_args(SomeClass) is not SomeClass
 
     def test_pytest_mark_name_starts_with_underscore(self):
         mark = Mark()
-        pytest.raises(AttributeError, getattr, mark, '_some_name')
+        pytest.raises(AttributeError, getattr, mark, "_some_name")
 
     def test_pytest_mark_bare(self):
         mark = Mark()
 
         def f():
             pass
 
         mark.hello(f)
         assert f.hello
 
+    @ignore_markinfo
     def test_pytest_mark_keywords(self):
         mark = Mark()
 
         def f():
             pass
 
         mark.world(x=3, y=4)(f)
         assert f.world
-        assert f.world.kwargs['x'] == 3
-        assert f.world.kwargs['y'] == 4
+        assert f.world.kwargs["x"] == 3
+        assert f.world.kwargs["y"] == 4
 
+    @ignore_markinfo
     def test_apply_multiple_and_merge(self):
         mark = Mark()
 
         def f():
             pass
 
         mark.world
         mark.world(x=3)(f)
-        assert f.world.kwargs['x'] == 3
+        assert f.world.kwargs["x"] == 3
         mark.world(y=4)(f)
-        assert f.world.kwargs['x'] == 3
-        assert f.world.kwargs['y'] == 4
+        assert f.world.kwargs["x"] == 3
+        assert f.world.kwargs["y"] == 4
         mark.world(y=1)(f)
-        assert f.world.kwargs['y'] == 1
+        assert f.world.kwargs["y"] == 1
         assert len(f.world.args) == 0
 
+    @ignore_markinfo
     def test_pytest_mark_positional(self):
         mark = Mark()
 
         def f():
             pass
 
         mark.world("hello")(f)
         assert f.world.args[0] == "hello"
         mark.world("world")(f)
 
+    @ignore_markinfo
     def test_pytest_mark_positional_func_and_keyword(self):
         mark = Mark()
 
         def f():
             raise Exception
 
         m = mark.world(f, omega="hello")
 
         def g():
             pass
 
         assert m(g) == g
         assert g.world.args[0] is f
         assert g.world.kwargs["omega"] == "hello"
 
+    @ignore_markinfo
     def test_pytest_mark_reuse(self):
         mark = Mark()
 
         def f():
             pass
 
         w = mark.some
         w("hello", reason="123")(f)
         assert f.some.args[0] == "hello"
-        assert f.some.kwargs['reason'] == "123"
+        assert f.some.kwargs["reason"] == "123"
 
         def g():
             pass
 
         w("world", reason2="456")(g)
         assert g.some.args[0] == "world"
-        assert 'reason' not in g.some.kwargs
-        assert g.some.kwargs['reason2'] == "456"
+        assert "reason" not in g.some.kwargs
+        assert g.some.kwargs["reason2"] == "456"
 
 
 def test_marked_class_run_twice(testdir, request):
     """Test fails file is run twice that contains marked class.
     See issue#683.
     """
-    py_file = testdir.makepyfile("""
+    py_file = testdir.makepyfile(
+        """
     import pytest
     @pytest.mark.parametrize('abc', [1, 2, 3])
     class Test1(object):
         def test_1(self, abc):
             assert abc in [1, 2, 3]
-    """)
+    """
+    )
     file_name = os.path.basename(py_file.strpath)
     rec = testdir.inline_run(file_name, file_name)
     rec.assertoutcome(passed=6)
 
 
 def test_ini_markers(testdir):
-    testdir.makeini("""
+    testdir.makeini(
+        """
         [pytest]
         markers =
             a1: this is a webtest marker
             a2: this is a smoke marker
-    """)
-    testdir.makepyfile("""
+    """
+    )
+    testdir.makepyfile(
+        """
         def test_markers(pytestconfig):
             markers = pytestconfig.getini("markers")
             print (markers)
             assert len(markers) >= 2
             assert markers[0].startswith("a1:")
             assert markers[1].startswith("a2:")
-    """)
+    """
+    )
     rec = testdir.inline_run()
     rec.assertoutcome(passed=1)
 
 
 def test_markers_option(testdir):
-    testdir.makeini("""
+    testdir.makeini(
+        """
         [pytest]
         markers =
             a1: this is a webtest marker
             a1some: another marker
             nodescription
-    """)
-    result = testdir.runpytest("--markers", )
-    result.stdout.fnmatch_lines([
-        "*a1*this is a webtest*",
-        "*a1some*another marker",
-        "*nodescription*",
-    ])
+    """
+    )
+    result = testdir.runpytest("--markers")
+    result.stdout.fnmatch_lines(
+        ["*a1*this is a webtest*", "*a1some*another marker", "*nodescription*"]
+    )
 
 
 def test_ini_markers_whitespace(testdir):
-    testdir.makeini("""
+    testdir.makeini(
+        """
         [pytest]
         markers =
             a1 : this is a whitespace marker
-    """)
-    testdir.makepyfile("""
+    """
+    )
+    testdir.makepyfile(
+        """
         import pytest
 
         @pytest.mark.a1
         def test_markers():
             assert True
-    """)
+    """
+    )
     rec = testdir.inline_run("--strict", "-m", "a1")
     rec.assertoutcome(passed=1)
 
 
 def test_marker_without_description(testdir):
-    testdir.makefile(".cfg", setup="""
+    testdir.makefile(
+        ".cfg",
+        setup="""
         [tool:pytest]
         markers=slow
-    """)
-    testdir.makeconftest("""
+    """,
+    )
+    testdir.makeconftest(
+        """
         import pytest
         pytest.mark.xfail('FAIL')
-    """)
+    """
+    )
     ftdir = testdir.mkdir("ft1_dummy")
     testdir.tmpdir.join("conftest.py").move(ftdir.join("conftest.py"))
     rec = testdir.runpytest_subprocess("--strict")
     rec.assert_outcomes()
 
 
 def test_markers_option_with_plugin_in_current_dir(testdir):
     testdir.makeconftest('pytest_plugins = "flip_flop"')
-    testdir.makepyfile(flip_flop="""\
+    testdir.makepyfile(
+        flip_flop="""\
         def pytest_configure(config):
             config.addinivalue_line("markers", "flip:flop")
 
         def pytest_generate_tests(metafunc):
             try:
                 mark = metafunc.function.flipper
             except AttributeError:
                 return
-            metafunc.parametrize("x", (10, 20))""")
-    testdir.makepyfile("""\
+            metafunc.parametrize("x", (10, 20))"""
+    )
+    testdir.makepyfile(
+        """\
         import pytest
         @pytest.mark.flipper
         def test_example(x):
-            assert x""")
+            assert x"""
+    )
 
     result = testdir.runpytest("--markers")
     result.stdout.fnmatch_lines(["*flip*flop*"])
 
 
 def test_mark_on_pseudo_function(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
 
         @pytest.mark.r(lambda x: 0/0)
         def test_hello():
             pass
-    """)
+    """
+    )
     reprec = testdir.inline_run()
     reprec.assertoutcome(passed=1)
 
 
 def test_strict_prohibits_unregistered_markers(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         @pytest.mark.unregisteredmark
         def test_hello():
             pass
-    """)
+    """
+    )
     result = testdir.runpytest("--strict")
     assert result.ret != 0
-    result.stdout.fnmatch_lines([
-        "*unregisteredmark*not*registered*",
-    ])
+    result.stdout.fnmatch_lines(["*unregisteredmark*not*registered*"])
 
 
-@pytest.mark.parametrize("spec", [
-    ("xyz", ("test_one",)),
-    ("xyz and xyz2", ()),
-    ("xyz2", ("test_two",)),
-    ("xyz or xyz2", ("test_one", "test_two"),)
-])
+@pytest.mark.parametrize(
+    "spec",
+    [
+        ("xyz", ("test_one",)),
+        ("xyz and xyz2", ()),
+        ("xyz2", ("test_two",)),
+        ("xyz or xyz2", ("test_one", "test_two")),
+    ],
+)
 def test_mark_option(spec, testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         @pytest.mark.xyz
         def test_one():
             pass
         @pytest.mark.xyz2
         def test_two():
             pass
-    """)
+    """
+    )
+    opt, passed_result = spec
+    rec = testdir.inline_run("-m", opt)
+    passed, skipped, fail = rec.listoutcomes()
+    passed = [x.nodeid.split("::")[-1] for x in passed]
+    assert len(passed) == len(passed_result)
+    assert list(passed) == list(passed_result)
+
+
+@pytest.mark.parametrize(
+    "spec", [("interface", ("test_interface",)), ("not interface", ("test_nointer",))]
+)
+def test_mark_option_custom(spec, testdir):
+    testdir.makeconftest(
+        """
+        import pytest
+        def pytest_collection_modifyitems(items):
+            for item in items:
+                if "interface" in item.nodeid:
+                    item.add_marker(pytest.mark.interface)
+    """
+    )
+    testdir.makepyfile(
+        """
+        def test_interface():
+            pass
+        def test_nointer():
+            pass
+    """
+    )
     opt, passed_result = spec
     rec = testdir.inline_run("-m", opt)
     passed, skipped, fail = rec.listoutcomes()
     passed = [x.nodeid.split("::")[-1] for x in passed]
     assert len(passed) == len(passed_result)
     assert list(passed) == list(passed_result)
 
 
-@pytest.mark.parametrize("spec", [
-    ("interface", ("test_interface",)),
-    ("not interface", ("test_nointer",)),
-])
-def test_mark_option_custom(spec, testdir):
-    testdir.makeconftest("""
-        import pytest
-        def pytest_collection_modifyitems(items):
-            for item in items:
-                if "interface" in item.nodeid:
-                    item.keywords["interface"] = pytest.mark.interface
-    """)
-    testdir.makepyfile("""
+@pytest.mark.parametrize(
+    "spec",
+    [
+        ("interface", ("test_interface",)),
+        ("not interface", ("test_nointer", "test_pass")),
+        ("pass", ("test_pass",)),
+        ("not pass", ("test_interface", "test_nointer")),
+    ],
+)
+def test_keyword_option_custom(spec, testdir):
+    testdir.makepyfile(
+        """
         def test_interface():
             pass
         def test_nointer():
             pass
-    """)
+        def test_pass():
+            pass
+    """
+    )
     opt, passed_result = spec
-    rec = testdir.inline_run("-m", opt)
+    rec = testdir.inline_run("-k", opt)
     passed, skipped, fail = rec.listoutcomes()
     passed = [x.nodeid.split("::")[-1] for x in passed]
     assert len(passed) == len(passed_result)
     assert list(passed) == list(passed_result)
 
 
-@pytest.mark.parametrize("spec", [
-    ("interface", ("test_interface",)),
-    ("not interface", ("test_nointer", "test_pass")),
-    ("pass", ("test_pass",)),
-    ("not pass", ("test_interface", "test_nointer")),
-])
-def test_keyword_option_custom(spec, testdir):
-    testdir.makepyfile("""
-        def test_interface():
+@pytest.mark.parametrize(
+    "spec",
+    [
+        ("None", ("test_func[None]",)),
+        ("1.3", ("test_func[1.3]",)),
+        ("2-3", ("test_func[2-3]",)),
+    ],
+)
+def test_keyword_option_parametrize(spec, testdir):
+    testdir.makepyfile(
+        """
+        import pytest
+        @pytest.mark.parametrize("arg", [None, 1.3, "2-3"])
+        def test_func(arg):
             pass
-        def test_nointer():
-            pass
-        def test_pass():
-            pass
-    """)
+    """
+    )
     opt, passed_result = spec
     rec = testdir.inline_run("-k", opt)
     passed, skipped, fail = rec.listoutcomes()
     passed = [x.nodeid.split("::")[-1] for x in passed]
     assert len(passed) == len(passed_result)
     assert list(passed) == list(passed_result)
 
 
-@pytest.mark.parametrize("spec", [
-    ("None", ("test_func[None]",)),
-    ("1.3", ("test_func[1.3]",)),
-    ("2-3", ("test_func[2-3]",))
-])
-def test_keyword_option_parametrize(spec, testdir):
-    testdir.makepyfile("""
-        import pytest
-        @pytest.mark.parametrize("arg", [None, 1.3, "2-3"])
-        def test_func(arg):
-            pass
-    """)
-    opt, passed_result = spec
-    rec = testdir.inline_run("-k", opt)
-    passed, skipped, fail = rec.listoutcomes()
-    passed = [x.nodeid.split("::")[-1] for x in passed]
-    assert len(passed) == len(passed_result)
-    assert list(passed) == list(passed_result)
+@pytest.mark.parametrize(
+    "spec",
+    [
+        (
+            "foo or import",
+            "ERROR: Python keyword 'import' not accepted in expressions passed to '-k'",
+        ),
+        ("foo or", "ERROR: Wrong expression passed to '-k': foo or"),
+    ],
+)
+def test_keyword_option_wrong_arguments(spec, testdir, capsys):
+    testdir.makepyfile(
+        """
+            def test_func(arg):
+                pass
+        """
+    )
+    opt, expected_result = spec
+    testdir.inline_run("-k", opt)
+    out = capsys.readouterr().err
+    assert expected_result in out
 
 
 def test_parametrized_collected_from_command_line(testdir):
     """Parametrized test not collected if test named specified
        in command line issue#649.
     """
-    py_file = testdir.makepyfile("""
+    py_file = testdir.makepyfile(
+        """
         import pytest
         @pytest.mark.parametrize("arg", [None, 1.3, "2-3"])
         def test_func(arg):
             pass
-    """)
+    """
+    )
     file_name = os.path.basename(py_file.strpath)
     rec = testdir.inline_run(file_name + "::" + "test_func")
     rec.assertoutcome(passed=3)
 
 
 def test_parametrized_collect_with_wrong_args(testdir):
     """Test collect parametrized func with wrong number of args."""
-    py_file = testdir.makepyfile("""
+    py_file = testdir.makepyfile(
+        """
         import pytest
 
         @pytest.mark.parametrize('foo, bar', [(1, 2, 3)])
         def test_func(foo, bar):
             pass
-    """)
+    """
+    )
 
     result = testdir.runpytest(py_file)
-    result.stdout.fnmatch_lines([
-        'E   ValueError: In "parametrize" the number of values ((1, 2, 3)) '
-        'must be equal to the number of names ([\'foo\', \'bar\'])'
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            'E   ValueError: In "parametrize" the number of values ((1, 2, 3)) '
+            "must be equal to the number of names (['foo', 'bar'])"
+        ]
+    )
 
 
 def test_parametrized_with_kwargs(testdir):
     """Test collect parametrized func with wrong number of args."""
-    py_file = testdir.makepyfile("""
+    py_file = testdir.makepyfile(
+        """
         import pytest
 
         @pytest.fixture(params=[1,2])
         def a(request):
             return request.param
 
         @pytest.mark.parametrize(argnames='b', argvalues=[1, 2])
         def test_func(a, b):
             pass
-    """)
+    """
+    )
 
     result = testdir.runpytest(py_file)
-    assert(result.ret == 0)
+    assert result.ret == 0
 
 
 class TestFunctional(object):
 
     def test_mark_per_function(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.hello
             def test_hello():
                 assert hasattr(test_hello, 'hello')
-        """)
+        """
+        )
         result = testdir.runpytest(p)
         result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_mark_per_module(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             pytestmark = pytest.mark.hello
             def test_func():
                 pass
-        """)
+        """
+        )
         keywords = item.keywords
-        assert 'hello' in keywords
+        assert "hello" in keywords
 
     def test_marklist_per_class(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             class TestClass(object):
                 pytestmark = [pytest.mark.hello, pytest.mark.world]
                 def test_func(self):
                     assert TestClass.test_func.hello
                     assert TestClass.test_func.world
-        """)
+        """
+        )
         keywords = item.keywords
-        assert 'hello' in keywords
+        assert "hello" in keywords
 
     def test_marklist_per_module(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             pytestmark = [pytest.mark.hello, pytest.mark.world]
             class TestClass(object):
                 def test_func(self):
                     assert TestClass.test_func.hello
                     assert TestClass.test_func.world
-        """)
+        """
+        )
         keywords = item.keywords
-        assert 'hello' in keywords
-        assert 'world' in keywords
+        assert "hello" in keywords
+        assert "world" in keywords
 
     def test_mark_per_class_decorator(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             @pytest.mark.hello
             class TestClass(object):
                 def test_func(self):
                     assert TestClass.test_func.hello
-        """)
+        """
+        )
         keywords = item.keywords
-        assert 'hello' in keywords
+        assert "hello" in keywords
 
     def test_mark_per_class_decorator_plus_existing_dec(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             @pytest.mark.hello
             class TestClass(object):
                 pytestmark = pytest.mark.world
                 def test_func(self):
                     assert TestClass.test_func.hello
                     assert TestClass.test_func.world
-        """)
+        """
+        )
         keywords = item.keywords
-        assert 'hello' in keywords
-        assert 'world' in keywords
+        assert "hello" in keywords
+        assert "world" in keywords
 
+    @ignore_markinfo
     def test_merging_markers(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             pytestmark = pytest.mark.hello("pos1", x=1, y=2)
             class TestClass(object):
                 # classlevel overrides module level
                 pytestmark = pytest.mark.hello(x=3)
                 @pytest.mark.hello("pos0", z=4)
                 def test_func(self):
                     pass
-        """)
+        """
+        )
         items, rec = testdir.inline_genitems(p)
         item, = items
         keywords = item.keywords
-        marker = keywords['hello']
+        marker = keywords["hello"]
         assert marker.args == ("pos0", "pos1")
-        assert marker.kwargs == {'x': 1, 'y': 2, 'z': 4}
+        assert marker.kwargs == {"x": 1, "y": 2, "z": 4}
 
         # test the new __iter__ interface
         values = list(marker)
         assert len(values) == 3
         assert values[0].args == ("pos0",)
         assert values[1].args == ()
-        assert values[2].args == ("pos1", )
+        assert values[2].args == ("pos1",)
 
-    @pytest.mark.xfail(reason='unfixed')
     def test_merging_markers_deep(self, testdir):
         # issue 199 - propagate markers into nested classes
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             class TestA(object):
                 pytestmark = pytest.mark.a
                 def test_b(self):
                     assert True
                 class TestC(object):
                     # this one didnt get marked
                     def test_d(self):
                         assert True
-        """)
+        """
+        )
         items, rec = testdir.inline_genitems(p)
         for item in items:
             print(item, item.keywords)
-            assert 'a' in item.keywords
+            assert [x for x in item.iter_markers() if x.name == "a"]
 
     def test_mark_decorator_subclass_does_not_propagate_to_base(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
 
             @pytest.mark.a
             class Base(object): pass
 
             @pytest.mark.b
             class Test1(Base):
                 def test_foo(self): pass
 
             class Test2(Base):
                 def test_bar(self): pass
-        """)
+        """
+        )
         items, rec = testdir.inline_genitems(p)
-        self.assert_markers(items, test_foo=('a', 'b'), test_bar=('a',))
+        self.assert_markers(items, test_foo=("a", "b"), test_bar=("a",))
 
     @pytest.mark.issue568
-    @pytest.mark.xfail(reason="markers smear on methods of base classes")
     def test_mark_should_not_pass_to_siebling_class(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
 
             class TestBase(object):
                 def test_foo(self):
                     pass
 
             @pytest.mark.b
             class TestSub(TestBase):
                 pass
 
 
             class TestOtherSub(TestBase):
                 pass
 
-        """)
+        """
+        )
         items, rec = testdir.inline_genitems(p)
         base_item, sub_item, sub_item_other = items
-        assert not hasattr(base_item.obj, 'b')
-        assert not hasattr(sub_item_other.obj, 'b')
+        print(items, [x.nodeid for x in items])
+        # legacy api smears
+        assert hasattr(base_item.obj, "b")
+        assert hasattr(sub_item_other.obj, "b")
+        assert hasattr(sub_item.obj, "b")
+
+        # new api seregates
+        assert not list(base_item.iter_markers(name="b"))
+        assert not list(sub_item_other.iter_markers(name="b"))
+        assert list(sub_item.iter_markers(name="b"))
 
     def test_mark_decorator_baseclasses_merged(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
 
             @pytest.mark.a
             class Base(object): pass
 
             @pytest.mark.b
             class Base2(Base): pass
 
             @pytest.mark.c
             class Test1(Base2):
                 def test_foo(self): pass
 
             class Test2(Base2):
                 @pytest.mark.d
                 def test_bar(self): pass
-        """)
+        """
+        )
         items, rec = testdir.inline_genitems(p)
-        self.assert_markers(items, test_foo=('a', 'b', 'c'),
-                            test_bar=('a', 'b', 'd'))
+        self.assert_markers(items, test_foo=("a", "b", "c"), test_bar=("a", "b", "d"))
+
+    def test_mark_closest(self, testdir):
+        p = testdir.makepyfile(
+            """
+            import pytest
+
+            @pytest.mark.c(location="class")
+            class Test:
+                @pytest.mark.c(location="function")
+                def test_has_own():
+                    pass
+
+                def test_has_inherited():
+                    pass
+
+        """
+        )
+        items, rec = testdir.inline_genitems(p)
+        has_own, has_inherited = items
+        assert has_own.get_closest_marker("c").kwargs == {"location": "function"}
+        assert has_inherited.get_closest_marker("c").kwargs == {"location": "class"}
+        assert has_own.get_closest_marker("missing") is None
 
     def test_mark_with_wrong_marker(self, testdir):
-        reprec = testdir.inline_runsource("""
+        reprec = testdir.inline_runsource(
+            """
                 import pytest
                 class pytestmark(object):
                     pass
                 def test_func():
                     pass
-        """)
+        """
+        )
         values = reprec.getfailedcollections()
         assert len(values) == 1
         assert "TypeError" in str(values[0].longrepr)
 
     def test_mark_dynamically_in_funcarg(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             @pytest.fixture
             def arg(request):
                 request.applymarker(pytest.mark.hello)
             def pytest_terminal_summary(terminalreporter):
                 values = terminalreporter.stats['passed']
                 terminalreporter._tw.line("keyword: %s" % values[0].keywords)
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             def test_func(arg):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "keyword: *hello*"
-        ])
+        result.stdout.fnmatch_lines(["keyword: *hello*"])
 
+    @ignore_markinfo
     def test_merging_markers_two_functions(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.hello("pos1", z=4)
             @pytest.mark.hello("pos0", z=3)
             def test_func():
                 pass
-        """)
+        """
+        )
         items, rec = testdir.inline_genitems(p)
         item, = items
         keywords = item.keywords
-        marker = keywords['hello']
+        marker = keywords["hello"]
         values = list(marker)
         assert len(values) == 2
         assert values[0].args == ("pos0",)
         assert values[1].args == ("pos1",)
 
     def test_no_marker_match_on_unmarked_names(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.shouldmatch
             def test_marked():
                 assert 1
 
             def test_unmarked():
                 assert 1
-        """)
+        """
+        )
         reprec = testdir.inline_run("-m", "test_unmarked", p)
         passed, skipped, failed = reprec.listoutcomes()
         assert len(passed) + len(skipped) + len(failed) == 0
         dlist = reprec.getcalls("pytest_deselected")
         deselected_tests = dlist[0].items
         assert len(deselected_tests) == 2
 
     def test_keywords_at_node_level(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture(scope="session", autouse=True)
             def some(request):
                 request.keywords["hello"] = 42
                 assert "world" not in request.keywords
 
             @pytest.fixture(scope="function", autouse=True)
             def funcsetup(request):
                 assert "world" in request.keywords
                 assert "hello" in  request.keywords
 
             @pytest.mark.world
             def test_function():
                 pass
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(passed=1)
 
+    @ignore_markinfo
     def test_keyword_added_for_session(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import pytest
             def pytest_collection_modifyitems(session):
                 session.add_marker("mark1")
                 session.add_marker(pytest.mark.mark2)
                 session.add_marker(pytest.mark.mark3)
                 pytest.raises(ValueError, lambda:
                         session.add_marker(10))
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             def test_some(request):
                 assert "mark1" in request.keywords
                 assert "mark2" in request.keywords
                 assert "mark3" in request.keywords
                 assert 10 not in request.keywords
                 marker = request.node.get_marker("mark1")
                 assert marker.name == "mark1"
                 assert marker.args == ()
                 assert marker.kwargs == {}
-        """)
+        """
+        )
         reprec = testdir.inline_run("-m", "mark1")
         reprec.assertoutcome(passed=1)
 
     def assert_markers(self, items, **expected):
         """assert that given items have expected marker names applied to them.
         expected should be a dict of (item name -> seq of expected marker names)
 
         .. note:: this could be moved to ``testdir`` if proven to be useful
         to other modules.
         """
         from _pytest.mark import MarkInfo
-        items = dict((x.name, x) for x in items)
+
+        items = {x.name: x for x in items}
         for name, expected_markers in expected.items():
             markers = items[name].keywords._markers
-            marker_names = set([name for (name, v) in markers.items()
-                                if isinstance(v, MarkInfo)])
+            marker_names = {
+                name for (name, v) in markers.items() if isinstance(v, MarkInfo)
+            }
             assert marker_names == set(expected_markers)
 
-    @pytest.mark.xfail(reason='callspec2.setmulti misuses keywords')
     @pytest.mark.issue1540
+    @pytest.mark.filterwarnings("ignore")
     def test_mark_from_parameters(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
 
             pytestmark = pytest.mark.skipif(True, reason='skip all')
 
             # skipifs inside fixture params
             params = [pytest.mark.skipif(False, reason='dont skip')('parameter')]
 
 
             @pytest.fixture(params=params)
             def parameter(request):
                 return request.param
 
 
             def test_1(parameter):
                 assert True
-        """)
+        """
+        )
         reprec = testdir.inline_run()
         reprec.assertoutcome(skipped=1)
 
 
 class TestKeywordSelection(object):
 
     def test_select_simple(self, testdir):
-        file_test = testdir.makepyfile("""
+        file_test = testdir.makepyfile(
+            """
             def test_one():
                 assert 0
             class TestClass(object):
                 def test_method_one(self):
                     assert 42 == 43
-        """)
+        """
+        )
 
         def check(keyword, name):
             reprec = testdir.inline_run("-s", "-k", keyword, file_test)
             passed, skipped, failed = reprec.listoutcomes()
             assert len(failed) == 1
             assert failed[0].nodeid.split("::")[-1] == name
-            assert len(reprec.getcalls('pytest_deselected')) == 1
+            assert len(reprec.getcalls("pytest_deselected")) == 1
 
-        for keyword in ['test_one', 'est_on']:
-            check(keyword, 'test_one')
-        check('TestClass and test', 'test_method_one')
+        for keyword in ["test_one", "est_on"]:
+            check(keyword, "test_one")
+        check("TestClass and test", "test_method_one")
 
-    @pytest.mark.parametrize("keyword", [
-        'xxx', 'xxx and test_2', 'TestClass', 'xxx and not test_1',
-        'TestClass and test_2', 'xxx and TestClass and test_2'])
+    @pytest.mark.parametrize(
+        "keyword",
+        [
+            "xxx",
+            "xxx and test_2",
+            "TestClass",
+            "xxx and not test_1",
+            "TestClass and test_2",
+            "xxx and TestClass and test_2",
+        ],
+    )
     def test_select_extra_keywords(self, testdir, keyword):
-        p = testdir.makepyfile(test_select="""
+        p = testdir.makepyfile(
+            test_select="""
             def test_1():
                 pass
             class TestClass(object):
                 def test_2(self):
                     pass
-        """)
-        testdir.makepyfile(conftest="""
+        """
+        )
+        testdir.makepyfile(
+            conftest="""
             import pytest
             @pytest.hookimpl(hookwrapper=True)
             def pytest_pycollect_makeitem(name):
                 outcome = yield
                 if name == "TestClass":
                     item = outcome.get_result()
                     item.extra_keyword_matches.add("xxx")
-        """)
-        reprec = testdir.inline_run(p.dirpath(), '-s', '-k', keyword)
+        """
+        )
+        reprec = testdir.inline_run(p.dirpath(), "-s", "-k", keyword)
         print("keyword", repr(keyword))
         passed, skipped, failed = reprec.listoutcomes()
         assert len(passed) == 1
         assert passed[0].nodeid.endswith("test_2")
         dlist = reprec.getcalls("pytest_deselected")
         assert len(dlist) == 1
-        assert dlist[0].items[0].name == 'test_1'
+        assert dlist[0].items[0].name == "test_1"
 
     def test_select_starton(self, testdir):
-        threepass = testdir.makepyfile(test_threepass="""
+        threepass = testdir.makepyfile(
+            test_threepass="""
             def test_one(): assert 1
             def test_two(): assert 1
             def test_three(): assert 1
-        """)
+        """
+        )
         reprec = testdir.inline_run("-k", "test_two:", threepass)
         passed, skipped, failed = reprec.listoutcomes()
         assert len(passed) == 2
         assert not failed
         dlist = reprec.getcalls("pytest_deselected")
         assert len(dlist) == 1
         item = dlist[0].items[0]
         assert item.name == "test_one"
 
     def test_keyword_extra(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
            def test_one():
                assert 0
            test_one.mykeyword = True
-        """)
+        """
+        )
         reprec = testdir.inline_run("-k", "mykeyword", p)
         passed, skipped, failed = reprec.countoutcomes()
         assert failed == 1
 
     @pytest.mark.xfail
     def test_keyword_extra_dash(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
            def test_one():
                assert 0
            test_one.mykeyword = True
-        """)
+        """
+        )
         # with argparse the argument to an option cannot
         # start with '-'
         reprec = testdir.inline_run("-k", "-mykeyword", p)
         passed, skipped, failed = reprec.countoutcomes()
         assert passed + skipped + failed == 0
 
     def test_no_magic_values(self, testdir):
         """Make sure the tests do not match on magic values,
         no double underscored values, like '__dict__',
         and no instance values, like '()'.
         """
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_one(): assert 1
-        """)
+        """
+        )
 
         def assert_test_is_not_selected(keyword):
             reprec = testdir.inline_run("-k", keyword, p)
             passed, skipped, failed = reprec.countoutcomes()
             dlist = reprec.getcalls("pytest_deselected")
             assert passed + skipped + failed == 0
             deselected_tests = dlist[0].items
             assert len(deselected_tests) == 1
 
         assert_test_is_not_selected("__")
         assert_test_is_not_selected("()")
 
 
-@pytest.mark.parametrize('argval, expected', [
-    (pytest.mark.skip()((1, 2)),
-     ParameterSet(values=(1, 2), marks=[pytest.mark.skip], id=None)),
-    (pytest.mark.xfail(pytest.mark.skip()((1, 2))),
-     ParameterSet(values=(1, 2),
-                  marks=[pytest.mark.xfail, pytest.mark.skip], id=None)),
-
-])
-@pytest.mark.filterwarnings('ignore')
+@pytest.mark.parametrize(
+    "argval, expected",
+    [
+        (
+            pytest.mark.skip()((1, 2)),
+            ParameterSet(values=(1, 2), marks=[pytest.mark.skip], id=None),
+        ),
+        (
+            pytest.mark.xfail(pytest.mark.skip()((1, 2))),
+            ParameterSet(
+                values=(1, 2), marks=[pytest.mark.xfail, pytest.mark.skip], id=None
+            ),
+        ),
+    ],
+)
+@pytest.mark.filterwarnings("ignore")
 def test_parameterset_extractfrom(argval, expected):
     extracted = ParameterSet.extract_from(argval)
     assert extracted == expected
 
 
 def test_legacy_transfer():
 
     class FakeModule(object):
@@ -863,16 +1050,85 @@ def test_legacy_transfer():
     assert fake_method.nofun
     assert fake_method.fun
     # pristine marks dont transfer
     assert fake_method.pytestmark == [pytest.mark.fun.mark]
 
 
 class TestMarkDecorator(object):
 
-    @pytest.mark.parametrize('lhs, rhs, expected', [
-        (pytest.mark.foo(), pytest.mark.foo(), True),
-        (pytest.mark.foo(), pytest.mark.bar(), False),
-        (pytest.mark.foo(), 'bar', False),
-        ('foo', pytest.mark.bar(), False)
-    ])
+    @pytest.mark.parametrize(
+        "lhs, rhs, expected",
+        [
+            (pytest.mark.foo(), pytest.mark.foo(), True),
+            (pytest.mark.foo(), pytest.mark.bar(), False),
+            (pytest.mark.foo(), "bar", False),
+            ("foo", pytest.mark.bar(), False),
+        ],
+    )
     def test__eq__(self, lhs, rhs, expected):
         assert (lhs == rhs) == expected
+
+
+@pytest.mark.parametrize("mark", [None, "", "skip", "xfail"])
+def test_parameterset_for_parametrize_marks(testdir, mark):
+    if mark is not None:
+        testdir.makeini("[pytest]\n{}={}".format(EMPTY_PARAMETERSET_OPTION, mark))
+
+    config = testdir.parseconfig()
+    from _pytest.mark import pytest_configure, get_empty_parameterset_mark
+
+    pytest_configure(config)
+    result_mark = get_empty_parameterset_mark(config, ["a"], all)
+    if mark in (None, ""):
+        # normalize to the requested name
+        mark = "skip"
+    assert result_mark.name == mark
+    assert result_mark.kwargs["reason"].startswith("got empty parameter set ")
+    if mark == "xfail":
+        assert result_mark.kwargs.get("run") is False
+
+
+def test_parameterset_for_parametrize_bad_markname(testdir):
+    with pytest.raises(pytest.UsageError):
+        test_parameterset_for_parametrize_marks(testdir, "bad")
+
+
+def test_mark_expressions_no_smear(testdir):
+    testdir.makepyfile(
+        """
+        import pytest
+
+        class BaseTests(object):
+            def test_something(self):
+                pass
+
+        @pytest.mark.FOO
+        class TestFooClass(BaseTests):
+            pass
+
+        @pytest.mark.BAR
+        class TestBarClass(BaseTests):
+            pass
+    """
+    )
+
+    reprec = testdir.inline_run("-m", "FOO")
+    passed, skipped, failed = reprec.countoutcomes()
+    dlist = reprec.getcalls("pytest_deselected")
+    assert passed == 1
+    assert skipped == failed == 0
+    deselected_tests = dlist[0].items
+    assert len(deselected_tests) == 1
+
+    # keywords smear - expected behaviour
+    reprec_keywords = testdir.inline_run("-k", "FOO")
+    passed_k, skipped_k, failed_k = reprec_keywords.countoutcomes()
+    assert passed_k == 2
+    assert skipped_k == failed_k == 0
+
+
+def test_addmarker_getmarker():
+    node = Node("Test", config=mock.Mock(), session=mock.Mock(), nodeid="Test")
+    node.add_marker(pytest.mark.a(1))
+    node.add_marker("b")
+    node.get_marker("a").combined
+    node.get_marker("b").combined
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_modimport.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_modimport.py
@@ -1,25 +1,29 @@
 import py
 import subprocess
 import sys
 import pytest
 import _pytest
 
 MODSET = [
-    x for x in py.path.local(_pytest.__file__).dirpath().visit('*.py')
-    if x.purebasename != '__init__'
+    x
+    for x in py.path.local(_pytest.__file__).dirpath().visit("*.py")
+    if x.purebasename != "__init__"
 ]
 
 
-@pytest.mark.parametrize('modfile', MODSET, ids=lambda x: x.purebasename)
+@pytest.mark.parametrize("modfile", MODSET, ids=lambda x: x.purebasename)
 def test_fileimport(modfile):
     # this test ensures all internal packages can import
     # without needing the pytest namespace being set
     # this is critical for the initialization of xdist
 
-    res = subprocess.call([
-        sys.executable,
-        '-c', 'import sys, py; py.path.local(sys.argv[1]).pyimport()',
-        modfile.strpath,
-    ])
+    res = subprocess.call(
+        [
+            sys.executable,
+            "-c",
+            "import sys, py; py.path.local(sys.argv[1]).pyimport()",
+            modfile.strpath,
+        ]
+    )
     if res:
         pytest.fail("command result %s" % res)
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_monkeypatch.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_monkeypatch.py
@@ -12,169 +12,175 @@ def mp():
     cwd = os.getcwd()
     sys_path = list(sys.path)
     yield MonkeyPatch()
     sys.path[:] = sys_path
     os.chdir(cwd)
 
 
 def test_setattr():
+
     class A(object):
         x = 1
 
     monkeypatch = MonkeyPatch()
     pytest.raises(AttributeError, "monkeypatch.setattr(A, 'notexists', 2)")
-    monkeypatch.setattr(A, 'y', 2, raising=False)
+    monkeypatch.setattr(A, "y", 2, raising=False)
     assert A.y == 2
     monkeypatch.undo()
-    assert not hasattr(A, 'y')
+    assert not hasattr(A, "y")
 
     monkeypatch = MonkeyPatch()
-    monkeypatch.setattr(A, 'x', 2)
+    monkeypatch.setattr(A, "x", 2)
     assert A.x == 2
-    monkeypatch.setattr(A, 'x', 3)
+    monkeypatch.setattr(A, "x", 3)
     assert A.x == 3
     monkeypatch.undo()
     assert A.x == 1
 
     A.x = 5
     monkeypatch.undo()  # double-undo makes no modification
     assert A.x == 5
 
 
 class TestSetattrWithImportPath(object):
+
     def test_string_expression(self, monkeypatch):
         monkeypatch.setattr("os.path.abspath", lambda x: "hello2")
         assert os.path.abspath("123") == "hello2"
 
     def test_string_expression_class(self, monkeypatch):
         monkeypatch.setattr("_pytest.config.Config", 42)
         import _pytest
+
         assert _pytest.config.Config == 42
 
     def test_unicode_string(self, monkeypatch):
         monkeypatch.setattr("_pytest.config.Config", 42)
         import _pytest
+
         assert _pytest.config.Config == 42
         monkeypatch.delattr("_pytest.config.Config")
 
     def test_wrong_target(self, monkeypatch):
         pytest.raises(TypeError, lambda: monkeypatch.setattr(None, None))
 
     def test_unknown_import(self, monkeypatch):
-        pytest.raises(ImportError,
-                      lambda: monkeypatch.setattr("unkn123.classx", None))
+        pytest.raises(ImportError, lambda: monkeypatch.setattr("unkn123.classx", None))
 
     def test_unknown_attr(self, monkeypatch):
-        pytest.raises(AttributeError,
-                      lambda: monkeypatch.setattr("os.path.qweqwe", None))
+        pytest.raises(
+            AttributeError, lambda: monkeypatch.setattr("os.path.qweqwe", None)
+        )
 
     def test_unknown_attr_non_raising(self, monkeypatch):
         # https://github.com/pytest-dev/pytest/issues/746
-        monkeypatch.setattr('os.path.qweqwe', 42, raising=False)
+        monkeypatch.setattr("os.path.qweqwe", 42, raising=False)
         assert os.path.qweqwe == 42
 
     def test_delattr(self, monkeypatch):
         monkeypatch.delattr("os.path.abspath")
         assert not hasattr(os.path, "abspath")
         monkeypatch.undo()
         assert os.path.abspath
 
 
 def test_delattr():
+
     class A(object):
         x = 1
 
     monkeypatch = MonkeyPatch()
-    monkeypatch.delattr(A, 'x')
-    assert not hasattr(A, 'x')
+    monkeypatch.delattr(A, "x")
+    assert not hasattr(A, "x")
     monkeypatch.undo()
     assert A.x == 1
 
     monkeypatch = MonkeyPatch()
-    monkeypatch.delattr(A, 'x')
+    monkeypatch.delattr(A, "x")
     pytest.raises(AttributeError, "monkeypatch.delattr(A, 'y')")
-    monkeypatch.delattr(A, 'y', raising=False)
-    monkeypatch.setattr(A, 'x', 5, raising=False)
+    monkeypatch.delattr(A, "y", raising=False)
+    monkeypatch.setattr(A, "x", 5, raising=False)
     assert A.x == 5
     monkeypatch.undo()
     assert A.x == 1
 
 
 def test_setitem():
-    d = {'x': 1}
+    d = {"x": 1}
     monkeypatch = MonkeyPatch()
-    monkeypatch.setitem(d, 'x', 2)
-    monkeypatch.setitem(d, 'y', 1700)
-    monkeypatch.setitem(d, 'y', 1700)
-    assert d['x'] == 2
-    assert d['y'] == 1700
-    monkeypatch.setitem(d, 'x', 3)
-    assert d['x'] == 3
+    monkeypatch.setitem(d, "x", 2)
+    monkeypatch.setitem(d, "y", 1700)
+    monkeypatch.setitem(d, "y", 1700)
+    assert d["x"] == 2
+    assert d["y"] == 1700
+    monkeypatch.setitem(d, "x", 3)
+    assert d["x"] == 3
     monkeypatch.undo()
-    assert d['x'] == 1
-    assert 'y' not in d
-    d['x'] = 5
+    assert d["x"] == 1
+    assert "y" not in d
+    d["x"] = 5
     monkeypatch.undo()
-    assert d['x'] == 5
+    assert d["x"] == 5
 
 
 def test_setitem_deleted_meanwhile():
     d = {}
     monkeypatch = MonkeyPatch()
-    monkeypatch.setitem(d, 'x', 2)
-    del d['x']
+    monkeypatch.setitem(d, "x", 2)
+    del d["x"]
     monkeypatch.undo()
     assert not d
 
 
 @pytest.mark.parametrize("before", [True, False])
 def test_setenv_deleted_meanwhile(before):
     key = "qwpeoip123"
     if before:
         os.environ[key] = "world"
     monkeypatch = MonkeyPatch()
-    monkeypatch.setenv(key, 'hello')
+    monkeypatch.setenv(key, "hello")
     del os.environ[key]
     monkeypatch.undo()
     if before:
         assert os.environ[key] == "world"
         del os.environ[key]
     else:
         assert key not in os.environ
 
 
 def test_delitem():
-    d = {'x': 1}
+    d = {"x": 1}
     monkeypatch = MonkeyPatch()
-    monkeypatch.delitem(d, 'x')
-    assert 'x' not in d
-    monkeypatch.delitem(d, 'y', raising=False)
+    monkeypatch.delitem(d, "x")
+    assert "x" not in d
+    monkeypatch.delitem(d, "y", raising=False)
     pytest.raises(KeyError, "monkeypatch.delitem(d, 'y')")
     assert not d
-    monkeypatch.setitem(d, 'y', 1700)
-    assert d['y'] == 1700
-    d['hello'] = 'world'
-    monkeypatch.setitem(d, 'x', 1500)
-    assert d['x'] == 1500
+    monkeypatch.setitem(d, "y", 1700)
+    assert d["y"] == 1700
+    d["hello"] = "world"
+    monkeypatch.setitem(d, "x", 1500)
+    assert d["x"] == 1500
     monkeypatch.undo()
-    assert d == {'hello': 'world', 'x': 1}
+    assert d == {"hello": "world", "x": 1}
 
 
 def test_setenv():
     monkeypatch = MonkeyPatch()
-    monkeypatch.setenv('XYZ123', 2)
+    monkeypatch.setenv("XYZ123", 2)
     import os
-    assert os.environ['XYZ123'] == "2"
+
+    assert os.environ["XYZ123"] == "2"
     monkeypatch.undo()
-    assert 'XYZ123' not in os.environ
+    assert "XYZ123" not in os.environ
 
 
 def test_delenv():
-    name = 'xyz1234'
+    name = "xyz1234"
     assert name not in os.environ
     monkeypatch = MonkeyPatch()
     pytest.raises(KeyError, "monkeypatch.delenv(%r, raising=True)" % name)
     monkeypatch.delenv(name, raising=False)
     monkeypatch.undo()
     os.environ[name] = "1"
     try:
         monkeypatch = MonkeyPatch()
@@ -186,52 +192,55 @@ def test_delenv():
         assert os.environ[name] == "1"
     finally:
         if name in os.environ:
             del os.environ[name]
 
 
 def test_setenv_prepend():
     import os
+
     monkeypatch = MonkeyPatch()
-    monkeypatch.setenv('XYZ123', 2, prepend="-")
-    assert os.environ['XYZ123'] == "2"
-    monkeypatch.setenv('XYZ123', 3, prepend="-")
-    assert os.environ['XYZ123'] == "3-2"
+    monkeypatch.setenv("XYZ123", 2, prepend="-")
+    assert os.environ["XYZ123"] == "2"
+    monkeypatch.setenv("XYZ123", 3, prepend="-")
+    assert os.environ["XYZ123"] == "3-2"
     monkeypatch.undo()
-    assert 'XYZ123' not in os.environ
+    assert "XYZ123" not in os.environ
 
 
 def test_monkeypatch_plugin(testdir):
-    reprec = testdir.inline_runsource("""
+    reprec = testdir.inline_runsource(
+        """
         def test_method(monkeypatch):
             assert monkeypatch.__class__.__name__ == "MonkeyPatch"
-    """)
+    """
+    )
     res = reprec.countoutcomes()
     assert tuple(res) == (1, 0, 0), res
 
 
 def test_syspath_prepend(mp):
     old = list(sys.path)
-    mp.syspath_prepend('world')
-    mp.syspath_prepend('hello')
+    mp.syspath_prepend("world")
+    mp.syspath_prepend("hello")
     assert sys.path[0] == "hello"
     assert sys.path[1] == "world"
     mp.undo()
     assert sys.path == old
     mp.undo()
     assert sys.path == old
 
 
 def test_syspath_prepend_double_undo(mp):
-    mp.syspath_prepend('hello world')
+    mp.syspath_prepend("hello world")
     mp.undo()
-    sys.path.append('more hello world')
+    sys.path.append("more hello world")
     mp.undo()
-    assert sys.path[-1] == 'more hello world'
+    assert sys.path[-1] == "more hello world"
 
 
 def test_chdir_with_path_local(mp, tmpdir):
     mp.chdir(tmpdir)
     assert os.getcwd() == tmpdir.strpath
 
 
 def test_chdir_with_str(mp, tmpdir):
@@ -250,47 +259,64 @@ def test_chdir_double_undo(mp, tmpdir):
     mp.chdir(tmpdir.strpath)
     mp.undo()
     tmpdir.chdir()
     mp.undo()
     assert os.getcwd() == tmpdir.strpath
 
 
 def test_issue185_time_breaks(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import time
         def test_m(monkeypatch):
             def f():
                 raise Exception
             monkeypatch.setattr(time, "time", f)
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines("""
+    result.stdout.fnmatch_lines(
+        """
         *1 passed*
-    """)
+    """
+    )
 
 
 def test_importerror(testdir):
     p = testdir.mkpydir("package")
-    p.join("a.py").write(textwrap.dedent("""\
+    p.join("a.py").write(
+        textwrap.dedent(
+            """\
         import doesnotexist
 
         x = 1
-    """))
-    testdir.tmpdir.join("test_importerror.py").write(textwrap.dedent("""\
+    """
+        )
+    )
+    testdir.tmpdir.join("test_importerror.py").write(
+        textwrap.dedent(
+            """\
         def test_importerror(monkeypatch):
             monkeypatch.setattr('package.a.x', 2)
-    """))
+    """
+        )
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines("""
+    result.stdout.fnmatch_lines(
+        """
         *import error in package.a: No module named {0}doesnotexist{0}*
-    """.format("'" if sys.version_info > (3, 0) else ""))
+    """.format(
+            "'" if sys.version_info > (3, 0) else ""
+        )
+    )
 
 
 class SampleNew(object):
+
     @staticmethod
     def hello():
         return True
 
 
 class SampleNewInherit(SampleNew):
     pass
 
@@ -301,29 +327,42 @@ class SampleOld(object):
     def hello():
         return True
 
 
 class SampleOldInherit(SampleOld):
     pass
 
 
-@pytest.mark.parametrize('Sample', [
-    SampleNew, SampleNewInherit,
-    SampleOld, SampleOldInherit,
-], ids=['new', 'new-inherit', 'old', 'old-inherit'])
+@pytest.mark.parametrize(
+    "Sample",
+    [SampleNew, SampleNewInherit, SampleOld, SampleOldInherit],
+    ids=["new", "new-inherit", "old", "old-inherit"],
+)
 def test_issue156_undo_staticmethod(Sample):
     monkeypatch = MonkeyPatch()
 
-    monkeypatch.setattr(Sample, 'hello', None)
+    monkeypatch.setattr(Sample, "hello", None)
     assert Sample.hello is None
 
     monkeypatch.undo()
     assert Sample.hello()
 
 
 def test_issue1338_name_resolving():
-    pytest.importorskip('requests')
+    pytest.importorskip("requests")
     monkeypatch = MonkeyPatch()
     try:
-        monkeypatch.delattr('requests.sessions.Session.request')
+        monkeypatch.delattr("requests.sessions.Session.request")
     finally:
         monkeypatch.undo()
+
+
+def test_context():
+    monkeypatch = MonkeyPatch()
+
+    import functools
+    import inspect
+
+    with monkeypatch.context() as m:
+        m.setattr(functools, "partial", 3)
+        assert not inspect.isclass(functools.partial)
+    assert inspect.isclass(functools.partial)
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_nodes.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_nodes.py
@@ -1,18 +1,21 @@
 import pytest
 
 from _pytest import nodes
 
 
-@pytest.mark.parametrize("baseid, nodeid, expected", (
-    ('', '', True),
-    ('', 'foo', True),
-    ('', 'foo/bar', True),
-    ('', 'foo/bar::TestBaz::()', True),
-    ('foo', 'food', False),
-    ('foo/bar::TestBaz::()', 'foo/bar', False),
-    ('foo/bar::TestBaz::()', 'foo/bar::TestBop::()', False),
-    ('foo/bar', 'foo/bar::TestBop::()', True),
-))
+@pytest.mark.parametrize(
+    "baseid, nodeid, expected",
+    (
+        ("", "", True),
+        ("", "foo", True),
+        ("", "foo/bar", True),
+        ("", "foo/bar::TestBaz::()", True),
+        ("foo", "food", False),
+        ("foo/bar::TestBaz::()", "foo/bar", False),
+        ("foo/bar::TestBaz::()", "foo/bar::TestBop::()", False),
+        ("foo/bar", "foo/bar::TestBop::()", True),
+    ),
+)
 def test_ischildnode(baseid, nodeid, expected):
     result = nodes.ischildnode(baseid, nodeid)
     assert result is expected
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_nose.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_nose.py
@@ -2,39 +2,43 @@ from __future__ import absolute_import, 
 import pytest
 
 
 def setup_module(mod):
     mod.nose = pytest.importorskip("nose")
 
 
 def test_nose_setup(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         values = []
         from nose.tools import with_setup
 
         @with_setup(lambda: values.append(1), lambda: values.append(2))
         def test_hello():
             assert values == [1]
 
         def test_world():
             assert values == [1,2]
 
         test_hello.setup = lambda: values.append(1)
         test_hello.teardown = lambda: values.append(2)
-    """)
-    result = testdir.runpytest(p, '-p', 'nose')
+    """
+    )
+    result = testdir.runpytest(p, "-p", "nose")
     result.assert_outcomes(passed=2)
 
 
 def test_setup_func_with_setup_decorator():
     from _pytest.nose import call_optional
+
     values = []
 
     class A(object):
+
         @pytest.fixture(autouse=True)
         def f(self):
             values.append(1)
 
     call_optional(A(), "f")
     assert not values
 
 
@@ -43,17 +47,18 @@ def test_setup_func_not_callable():
 
     class A(object):
         f = 1
 
     call_optional(A(), "f")
 
 
 def test_nose_setup_func(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         from nose.tools import with_setup
 
         values = []
 
         def my_setup():
             a = 1
             values.append(a)
 
@@ -65,65 +70,69 @@ def test_nose_setup_func(testdir):
         def test_hello():
             print (values)
             assert values == [1]
 
         def test_world():
             print (values)
             assert values == [1,2]
 
-    """)
-    result = testdir.runpytest(p, '-p', 'nose')
+    """
+    )
+    result = testdir.runpytest(p, "-p", "nose")
     result.assert_outcomes(passed=2)
 
 
 def test_nose_setup_func_failure(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         from nose.tools import with_setup
 
         values = []
         my_setup = lambda x: 1
         my_teardown = lambda x: 2
 
         @with_setup(my_setup, my_teardown)
         def test_hello():
             print (values)
             assert values == [1]
 
         def test_world():
             print (values)
             assert values == [1,2]
 
-    """)
-    result = testdir.runpytest(p, '-p', 'nose')
-    result.stdout.fnmatch_lines([
-        "*TypeError: <lambda>()*"
-    ])
+    """
+    )
+    result = testdir.runpytest(p, "-p", "nose")
+    result.stdout.fnmatch_lines(["*TypeError: <lambda>()*"])
 
 
 def test_nose_setup_func_failure_2(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         values = []
 
         my_setup = 1
         my_teardown = 2
 
         def test_hello():
             assert values == []
 
         test_hello.setup = my_setup
         test_hello.teardown = my_teardown
-    """)
+    """
+    )
     reprec = testdir.inline_run()
     reprec.assertoutcome(passed=1)
 
 
 def test_nose_setup_partial(testdir):
     pytest.importorskip("functools")
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         from functools import partial
 
         values = []
 
         def my_setup(x):
             a = x
             values.append(a)
 
@@ -139,25 +148,25 @@ def test_nose_setup_partial(testdir):
             assert values == [1]
 
         def test_world():
             print (values)
             assert values == [1,2]
 
         test_hello.setup = my_setup_partial
         test_hello.teardown = my_teardown_partial
-    """)
-    result = testdir.runpytest(p, '-p', 'nose')
-    result.stdout.fnmatch_lines([
-        "*2 passed*"
-    ])
+    """
+    )
+    result = testdir.runpytest(p, "-p", "nose")
+    result.stdout.fnmatch_lines(["*2 passed*"])
 
 
 def test_nose_test_generator_fixtures(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         # taken from nose-0.11.1 unit_tests/test_generator_fixtures.py
         from nose.tools import eq_
         called = []
 
         def outer_setup():
             called.append('outer_setup')
 
         def outer_teardown():
@@ -206,25 +215,25 @@ def test_nose_test_generator_fixtures(te
             def check(self, i):
                 print ("check called in %s" % self)
                 expect = ['setup']
                 #for x in range(0, i):
                 #    expect.append('setup')
                 #    expect.append('teardown')
                 #expect.append('setup')
                 eq_(self.called, expect)
-    """)
-    result = testdir.runpytest(p, '-p', 'nose')
-    result.stdout.fnmatch_lines([
-        "*10 passed*"
-    ])
+    """
+    )
+    result = testdir.runpytest(p, "-p", "nose")
+    result.stdout.fnmatch_lines(["*10 passed*"])
 
 
 def test_module_level_setup(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         from nose.tools import with_setup
         items = {}
 
         def setup():
             items[1]=1
 
         def teardown():
             del items[1]
@@ -237,89 +246,91 @@ def test_module_level_setup(testdir):
 
         def test_setup_module_setup():
             assert items[1] == 1
 
         @with_setup(setup2, teardown2)
         def test_local_setup():
             assert items[2] == 2
             assert 1 not in items
-    """)
-    result = testdir.runpytest('-p', 'nose')
-    result.stdout.fnmatch_lines([
-        "*2 passed*",
-    ])
+    """
+    )
+    result = testdir.runpytest("-p", "nose")
+    result.stdout.fnmatch_lines(["*2 passed*"])
 
 
 def test_nose_style_setup_teardown(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         values = []
 
         def setup_module():
             values.append(1)
 
         def teardown_module():
             del values[0]
 
         def test_hello():
             assert values == [1]
 
         def test_world():
             assert values == [1]
-        """)
-    result = testdir.runpytest('-p', 'nose')
-    result.stdout.fnmatch_lines([
-        "*2 passed*",
-    ])
+        """
+    )
+    result = testdir.runpytest("-p", "nose")
+    result.stdout.fnmatch_lines(["*2 passed*"])
 
 
 def test_nose_setup_ordering(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def setup_module(mod):
             mod.visited = True
 
         class TestClass(object):
             def setup(self):
                 assert visited
             def test_first(self):
                 pass
-        """)
+        """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        "*1 passed*",
-    ])
+    result.stdout.fnmatch_lines(["*1 passed*"])
 
 
 def test_apiwrapper_problem_issue260(testdir):
-    # this would end up trying a call a optional teardown on the class
+    # this would end up trying a call an optional teardown on the class
     # for plain unittests we dont want nose behaviour
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import unittest
         class TestCase(unittest.TestCase):
             def setup(self):
                 #should not be called in unittest testcases
                 assert 0, 'setup'
             def teardown(self):
                 #should not be called in unittest testcases
                 assert 0, 'teardown'
             def setUp(self):
                 print('setup')
             def tearDown(self):
                 print('teardown')
             def test_fun(self):
                 pass
-        """)
+        """
+    )
     result = testdir.runpytest()
     result.assert_outcomes(passed=1)
 
 
 def test_setup_teardown_linking_issue265(testdir):
     # we accidentally didnt integrate nose setupstate with normal setupstate
     # this test ensures that won't happen again
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        '''
         import pytest
 
         class TestGeneric(object):
             def test_nothing(self):
                 """Tests the API of the implementation (for generic and specialized)."""
 
         @pytest.mark.skipif("True", reason=
                     "Skip tests to check if teardown is skipped as well.")
@@ -327,83 +338,96 @@ def test_setup_teardown_linking_issue265
 
             def setup(self):
                 """Sets up my specialized implementation for $COOL_PLATFORM."""
                 raise Exception("should not call setup for skipped tests")
 
             def teardown(self):
                 """Undoes the setup."""
                 raise Exception("should not call teardown for skipped tests")
-        ''')
+        '''
+    )
     reprec = testdir.runpytest()
     reprec.assert_outcomes(passed=1, skipped=1)
 
 
 def test_SkipTest_during_collection(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         import nose
         raise nose.SkipTest("during collection")
         def test_failing():
             assert False
-        """)
+        """
+    )
     result = testdir.runpytest(p)
     result.assert_outcomes(skipped=1)
 
 
 def test_SkipTest_in_test(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import nose
 
         def test_skipping():
             raise nose.SkipTest("in test")
-        """)
+        """
+    )
     reprec = testdir.inline_run()
     reprec.assertoutcome(skipped=1)
 
 
 def test_istest_function_decorator(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         import nose.tools
         @nose.tools.istest
         def not_test_prefix():
             pass
-        """)
+        """
+    )
     result = testdir.runpytest(p)
     result.assert_outcomes(passed=1)
 
 
 def test_nottest_function_decorator(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import nose.tools
         @nose.tools.nottest
         def test_prefix():
             pass
-        """)
+        """
+    )
     reprec = testdir.inline_run()
     assert not reprec.getfailedcollections()
     calls = reprec.getreports("pytest_runtest_logreport")
     assert not calls
 
 
 def test_istest_class_decorator(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         import nose.tools
         @nose.tools.istest
         class NotTestPrefix(object):
             def test_method(self):
                 pass
-        """)
+        """
+    )
     result = testdir.runpytest(p)
     result.assert_outcomes(passed=1)
 
 
 def test_nottest_class_decorator(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import nose.tools
         @nose.tools.nottest
         class TestPrefix(object):
             def test_method(self):
                 pass
-        """)
+        """
+    )
     reprec = testdir.inline_run()
     assert not reprec.getfailedcollections()
     calls = reprec.getreports("pytest_runtest_logreport")
     assert not calls
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_parseopt.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_parseopt.py
@@ -1,67 +1,71 @@
 from __future__ import absolute_import, division, print_function
+import argparse
 import sys
 import os
 import py
 import pytest
-from _pytest import config as parseopt
+from _pytest.config import argparsing as parseopt
 
 
 @pytest.fixture
 def parser():
     return parseopt.Parser()
 
 
 class TestParser(object):
+
     def test_no_help_by_default(self, capsys):
         parser = parseopt.Parser(usage="xyz")
         pytest.raises(SystemExit, lambda: parser.parse(["-h"]))
         out, err = capsys.readouterr()
         assert err.find("error: unrecognized arguments") != -1
 
     def test_argument(self):
         with pytest.raises(parseopt.ArgumentError):
             # need a short or long option
             argument = parseopt.Argument()
-        argument = parseopt.Argument('-t')
-        assert argument._short_opts == ['-t']
+        argument = parseopt.Argument("-t")
+        assert argument._short_opts == ["-t"]
         assert argument._long_opts == []
-        assert argument.dest == 't'
-        argument = parseopt.Argument('-t', '--test')
-        assert argument._short_opts == ['-t']
-        assert argument._long_opts == ['--test']
-        assert argument.dest == 'test'
-        argument = parseopt.Argument('-t', '--test', dest='abc')
-        assert argument.dest == 'abc'
-        assert str(argument) == (
-            "Argument(_short_opts: ['-t'], _long_opts: ['--test'], dest: 'abc')"
+        assert argument.dest == "t"
+        argument = parseopt.Argument("-t", "--test")
+        assert argument._short_opts == ["-t"]
+        assert argument._long_opts == ["--test"]
+        assert argument.dest == "test"
+        argument = parseopt.Argument("-t", "--test", dest="abc")
+        assert argument.dest == "abc"
+        assert (
+            str(argument)
+            == ("Argument(_short_opts: ['-t'], _long_opts: ['--test'], dest: 'abc')")
         )
 
     def test_argument_type(self):
-        argument = parseopt.Argument('-t', dest='abc', type=int)
+        argument = parseopt.Argument("-t", dest="abc", type=int)
         assert argument.type is int
-        argument = parseopt.Argument('-t', dest='abc', type=str)
+        argument = parseopt.Argument("-t", dest="abc", type=str)
         assert argument.type is str
-        argument = parseopt.Argument('-t', dest='abc', type=float)
+        argument = parseopt.Argument("-t", dest="abc", type=float)
         assert argument.type is float
         with pytest.warns(DeprecationWarning):
             with pytest.raises(KeyError):
-                argument = parseopt.Argument('-t', dest='abc', type='choice')
-        argument = parseopt.Argument('-t', dest='abc', type=str,
-                                     choices=['red', 'blue'])
+                argument = parseopt.Argument("-t", dest="abc", type="choice")
+        argument = parseopt.Argument(
+            "-t", dest="abc", type=str, choices=["red", "blue"]
+        )
         assert argument.type is str
 
     def test_argument_processopt(self):
-        argument = parseopt.Argument('-t', type=int)
+        argument = parseopt.Argument("-t", type=int)
         argument.default = 42
-        argument.dest = 'abc'
+        argument.dest = "abc"
         res = argument.attrs()
-        assert res['default'] == 42
-        assert res['dest'] == 'abc'
+        assert res["default"] == 42
+        assert res["dest"] == "abc"
 
     def test_group_add_and_get(self, parser):
         group = parser.getgroup("hello", description="desc")
         assert group.name == "hello"
         assert group.description == "desc"
 
     def test_getgroup_simple(self, parser):
         group = parser.getgroup("hello", description="desc")
@@ -84,57 +88,61 @@ class TestParser(object):
         assert len(group.options) == 1
         assert isinstance(group.options[0], parseopt.Argument)
 
     def test_group_addoption_conflict(self):
         group = parseopt.OptionGroup("hello again")
         group.addoption("--option1", "--option-1", action="store_true")
         with pytest.raises(ValueError) as err:
             group.addoption("--option1", "--option-one", action="store_true")
-        assert str(set(["--option1"])) in str(err.value)
+        assert str({"--option1"}) in str(err.value)
 
     def test_group_shortopt_lowercase(self, parser):
         group = parser.getgroup("hello")
-        pytest.raises(ValueError, """
+        pytest.raises(
+            ValueError,
+            """
             group.addoption("-x", action="store_true")
-        """)
+        """,
+        )
         assert len(group.options) == 0
         group._addoption("-x", action="store_true")
         assert len(group.options) == 1
 
     def test_parser_addoption(self, parser):
         group = parser.getgroup("custom options")
         assert len(group.options) == 0
         group.addoption("--option1", action="store_true")
         assert len(group.options) == 1
 
     def test_parse(self, parser):
         parser.addoption("--hello", dest="hello", action="store")
-        args = parser.parse(['--hello', 'world'])
+        args = parser.parse(["--hello", "world"])
         assert args.hello == "world"
         assert not getattr(args, parseopt.FILE_OR_DIR)
 
     def test_parse2(self, parser):
         args = parser.parse([py.path.local()])
         assert getattr(args, parseopt.FILE_OR_DIR)[0] == py.path.local()
 
     def test_parse_known_args(self, parser):
         parser.parse_known_args([py.path.local()])
         parser.addoption("--hello", action="store_true")
         ns = parser.parse_known_args(["x", "--y", "--hello", "this"])
         assert ns.hello
-        assert ns.file_or_dir == ['x']
+        assert ns.file_or_dir == ["x"]
 
     def test_parse_known_and_unknown_args(self, parser):
         parser.addoption("--hello", action="store_true")
-        ns, unknown = parser.parse_known_and_unknown_args(["x", "--y",
-                                                           "--hello", "this"])
+        ns, unknown = parser.parse_known_and_unknown_args(
+            ["x", "--y", "--hello", "this"]
+        )
         assert ns.hello
-        assert ns.file_or_dir == ['x']
-        assert unknown == ['--y', 'this']
+        assert ns.file_or_dir == ["x"]
+        assert unknown == ["--y", "this"]
 
     def test_parse_will_set_default(self, parser):
         parser.addoption("--hello", dest="hello", default="x", action="store")
         option = parser.parse([])
         assert option.hello == "x"
         del option.hello
         parser.parse_setoption([], option)
         assert option.hello == "x"
@@ -142,168 +150,187 @@ class TestParser(object):
     def test_parse_setoption(self, parser):
         parser.addoption("--hello", dest="hello", action="store")
         parser.addoption("--world", dest="world", default=42)
 
         class A(object):
             pass
 
         option = A()
-        args = parser.parse_setoption(['--hello', 'world'], option)
+        args = parser.parse_setoption(["--hello", "world"], option)
         assert option.hello == "world"
         assert option.world == 42
         assert not args
 
     def test_parse_special_destination(self, parser):
         parser.addoption("--ultimate-answer", type=int)
-        args = parser.parse(['--ultimate-answer', '42'])
+        args = parser.parse(["--ultimate-answer", "42"])
         assert args.ultimate_answer == 42
 
     def test_parse_split_positional_arguments(self, parser):
-        parser.addoption("-R", action='store_true')
-        parser.addoption("-S", action='store_false')
-        args = parser.parse(['-R', '4', '2', '-S'])
-        assert getattr(args, parseopt.FILE_OR_DIR) == ['4', '2']
-        args = parser.parse(['-R', '-S', '4', '2', '-R'])
-        assert getattr(args, parseopt.FILE_OR_DIR) == ['4', '2']
+        parser.addoption("-R", action="store_true")
+        parser.addoption("-S", action="store_false")
+        args = parser.parse(["-R", "4", "2", "-S"])
+        assert getattr(args, parseopt.FILE_OR_DIR) == ["4", "2"]
+        args = parser.parse(["-R", "-S", "4", "2", "-R"])
+        assert getattr(args, parseopt.FILE_OR_DIR) == ["4", "2"]
         assert args.R is True
         assert args.S is False
-        args = parser.parse(['-R', '4', '-S', '2'])
-        assert getattr(args, parseopt.FILE_OR_DIR) == ['4', '2']
+        args = parser.parse(["-R", "4", "-S", "2"])
+        assert getattr(args, parseopt.FILE_OR_DIR) == ["4", "2"]
         assert args.R is True
         assert args.S is False
 
     def test_parse_defaultgetter(self):
+
         def defaultget(option):
-            if not hasattr(option, 'type'):
+            if not hasattr(option, "type"):
                 return
             if option.type is int:
                 option.default = 42
             elif option.type is str:
                 option.default = "world"
+
         parser = parseopt.Parser(processopt=defaultget)
         parser.addoption("--this", dest="this", type=int, action="store")
         parser.addoption("--hello", dest="hello", type=str, action="store")
         parser.addoption("--no", dest="no", action="store_true")
         option = parser.parse([])
         assert option.hello == "world"
         assert option.this == 42
         assert option.no is False
 
     def test_drop_short_helper(self):
-        parser = py.std.argparse.ArgumentParser(formatter_class=parseopt.DropShorterLongHelpFormatter)
-        parser.add_argument('-t', '--twoword', '--duo', '--two-word', '--two',
-                            help='foo').map_long_option = {'two': 'two-word'}
+        parser = argparse.ArgumentParser(
+            formatter_class=parseopt.DropShorterLongHelpFormatter
+        )
+        parser.add_argument(
+            "-t", "--twoword", "--duo", "--two-word", "--two", help="foo"
+        ).map_long_option = {
+            "two": "two-word"
+        }
         # throws error on --deux only!
-        parser.add_argument('-d', '--deuxmots', '--deux-mots',
-                            action='store_true', help='foo').map_long_option = {'deux': 'deux-mots'}
-        parser.add_argument('-s', action='store_true', help='single short')
-        parser.add_argument('--abc', '-a',
-                            action='store_true', help='bar')
-        parser.add_argument('--klm', '-k', '--kl-m',
-                            action='store_true', help='bar')
-        parser.add_argument('-P', '--pq-r', '-p', '--pqr',
-                            action='store_true', help='bar')
-        parser.add_argument('--zwei-wort', '--zweiwort', '--zweiwort',
-                            action='store_true', help='bar')
-        parser.add_argument('-x', '--exit-on-first', '--exitfirst',
-                            action='store_true', help='spam').map_long_option = {'exitfirst': 'exit-on-first'}
-        parser.add_argument('files_and_dirs', nargs='*')
-        args = parser.parse_args(['-k', '--duo', 'hallo', '--exitfirst'])
-        assert args.twoword == 'hallo'
+        parser.add_argument(
+            "-d", "--deuxmots", "--deux-mots", action="store_true", help="foo"
+        ).map_long_option = {
+            "deux": "deux-mots"
+        }
+        parser.add_argument("-s", action="store_true", help="single short")
+        parser.add_argument("--abc", "-a", action="store_true", help="bar")
+        parser.add_argument("--klm", "-k", "--kl-m", action="store_true", help="bar")
+        parser.add_argument(
+            "-P", "--pq-r", "-p", "--pqr", action="store_true", help="bar"
+        )
+        parser.add_argument(
+            "--zwei-wort", "--zweiwort", "--zweiwort", action="store_true", help="bar"
+        )
+        parser.add_argument(
+            "-x", "--exit-on-first", "--exitfirst", action="store_true", help="spam"
+        ).map_long_option = {
+            "exitfirst": "exit-on-first"
+        }
+        parser.add_argument("files_and_dirs", nargs="*")
+        args = parser.parse_args(["-k", "--duo", "hallo", "--exitfirst"])
+        assert args.twoword == "hallo"
         assert args.klm is True
         assert args.zwei_wort is False
         assert args.exit_on_first is True
         assert args.s is False
-        args = parser.parse_args(['--deux-mots'])
+        args = parser.parse_args(["--deux-mots"])
         with pytest.raises(AttributeError):
             assert args.deux_mots is True
         assert args.deuxmots is True
-        args = parser.parse_args(['file', 'dir'])
-        assert '|'.join(args.files_and_dirs) == 'file|dir'
+        args = parser.parse_args(["file", "dir"])
+        assert "|".join(args.files_and_dirs) == "file|dir"
 
     def test_drop_short_0(self, parser):
-        parser.addoption('--funcarg', '--func-arg', action='store_true')
-        parser.addoption('--abc-def', '--abc-def', action='store_true')
-        parser.addoption('--klm-hij', action='store_true')
-        args = parser.parse(['--funcarg', '--k'])
+        parser.addoption("--funcarg", "--func-arg", action="store_true")
+        parser.addoption("--abc-def", "--abc-def", action="store_true")
+        parser.addoption("--klm-hij", action="store_true")
+        args = parser.parse(["--funcarg", "--k"])
         assert args.funcarg is True
         assert args.abc_def is False
         assert args.klm_hij is True
 
     def test_drop_short_2(self, parser):
-        parser.addoption('--func-arg', '--doit', action='store_true')
-        args = parser.parse(['--doit'])
+        parser.addoption("--func-arg", "--doit", action="store_true")
+        args = parser.parse(["--doit"])
         assert args.func_arg is True
 
     def test_drop_short_3(self, parser):
-        parser.addoption('--func-arg', '--funcarg', '--doit', action='store_true')
-        args = parser.parse(['abcd'])
+        parser.addoption("--func-arg", "--funcarg", "--doit", action="store_true")
+        args = parser.parse(["abcd"])
         assert args.func_arg is False
-        assert args.file_or_dir == ['abcd']
+        assert args.file_or_dir == ["abcd"]
 
     def test_drop_short_help0(self, parser, capsys):
-        parser.addoption('--func-args', '--doit', help='foo',
-                         action='store_true')
+        parser.addoption("--func-args", "--doit", help="foo", action="store_true")
         parser.parse([])
         help = parser.optparser.format_help()
-        assert '--func-args, --doit  foo' in help
+        assert "--func-args, --doit  foo" in help
 
     # testing would be more helpful with all help generated
     def test_drop_short_help1(self, parser, capsys):
         group = parser.getgroup("general")
-        group.addoption('--doit', '--func-args', action='store_true', help='foo')
-        group._addoption("-h", "--help", action="store_true", dest="help",
-                         help="show help message and configuration info")
-        parser.parse(['-h'])
+        group.addoption("--doit", "--func-args", action="store_true", help="foo")
+        group._addoption(
+            "-h",
+            "--help",
+            action="store_true",
+            dest="help",
+            help="show help message and configuration info",
+        )
+        parser.parse(["-h"])
         help = parser.optparser.format_help()
-        assert '-doit, --func-args  foo' in help
+        assert "-doit, --func-args  foo" in help
 
     def test_multiple_metavar_help(self, parser):
         """
         Help text for options with a metavar tuple should display help
         in the form "--preferences=value1 value2 value3" (#2004).
         """
         group = parser.getgroup("general")
-        group.addoption('--preferences', metavar=('value1', 'value2', 'value3'), nargs=3)
+        group.addoption(
+            "--preferences", metavar=("value1", "value2", "value3"), nargs=3
+        )
         group._addoption("-h", "--help", action="store_true", dest="help")
-        parser.parse(['-h'])
+        parser.parse(["-h"])
         help = parser.optparser.format_help()
-        assert '--preferences=value1 value2 value3' in help
+        assert "--preferences=value1 value2 value3" in help
 
 
 def test_argcomplete(testdir, monkeypatch):
-    if not py.path.local.sysfind('bash'):
+    if not py.path.local.sysfind("bash"):
         pytest.skip("bash not available")
     script = str(testdir.tmpdir.join("test_argcomplete"))
     pytest_bin = sys.argv[0]
     if "pytest" not in os.path.basename(pytest_bin):
         pytest.skip("need to be run with pytest executable, not %s" % (pytest_bin,))
 
-    with open(str(script), 'w') as fp:
+    with open(str(script), "w") as fp:
         # redirect output from argcomplete to stdin and stderr is not trivial
         # http://stackoverflow.com/q/12589419/1307905
         # so we use bash
         fp.write('COMP_WORDBREAKS="$COMP_WORDBREAKS" %s 8>&1 9>&2' % pytest_bin)
     # alternative would be exteneded Testdir.{run(),_run(),popen()} to be able
     # to handle a keyword argument env that replaces os.environ in popen or
     # extends the copy, advantage: could not forget to restore
-    monkeypatch.setenv('_ARGCOMPLETE', "1")
-    monkeypatch.setenv('_ARGCOMPLETE_IFS', "\x0b")
-    monkeypatch.setenv('COMP_WORDBREAKS', ' \\t\\n"\\\'><=;|&(:')
+    monkeypatch.setenv("_ARGCOMPLETE", "1")
+    monkeypatch.setenv("_ARGCOMPLETE_IFS", "\x0b")
+    monkeypatch.setenv("COMP_WORDBREAKS", " \\t\\n\"\\'><=;|&(:")
 
-    arg = '--fu'
-    monkeypatch.setenv('COMP_LINE', "pytest " + arg)
-    monkeypatch.setenv('COMP_POINT', str(len("pytest " + arg)))
-    result = testdir.run('bash', str(script), arg)
+    arg = "--fu"
+    monkeypatch.setenv("COMP_LINE", "pytest " + arg)
+    monkeypatch.setenv("COMP_POINT", str(len("pytest " + arg)))
+    result = testdir.run("bash", str(script), arg)
     if result.ret == 255:
         # argcomplete not found
         pytest.skip("argcomplete not available")
     elif not result.stdout.str():
         pytest.skip("bash provided no output, argcomplete not available?")
     else:
         result.stdout.fnmatch_lines(["--funcargs", "--fulltrace"])
-    os.mkdir('test_argcomplete.d')
-    arg = 'test_argc'
-    monkeypatch.setenv('COMP_LINE', "pytest " + arg)
-    monkeypatch.setenv('COMP_POINT', str(len('pytest ' + arg)))
-    result = testdir.run('bash', str(script), arg)
+    os.mkdir("test_argcomplete.d")
+    arg = "test_argc"
+    monkeypatch.setenv("COMP_LINE", "pytest " + arg)
+    monkeypatch.setenv("COMP_POINT", str(len("pytest " + arg)))
+    result = testdir.run("bash", str(script), arg)
     result.stdout.fnmatch_lines(["test_argcomplete", "test_argcomplete.d/"])
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_pastebin.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_pastebin.py
@@ -4,114 +4,129 @@ import sys
 import pytest
 
 
 class TestPasteCapture(object):
 
     @pytest.fixture
     def pastebinlist(self, monkeypatch, request):
         pastebinlist = []
-        plugin = request.config.pluginmanager.getplugin('pastebin')
-        monkeypatch.setattr(plugin, 'create_new_paste', pastebinlist.append)
+        plugin = request.config.pluginmanager.getplugin("pastebin")
+        monkeypatch.setattr(plugin, "create_new_paste", pastebinlist.append)
         return pastebinlist
 
     def test_failed(self, testdir, pastebinlist):
-        testpath = testdir.makepyfile("""
+        testpath = testdir.makepyfile(
+            """
             import pytest
             def test_pass():
                 pass
             def test_fail():
                 assert 0
             def test_skip():
                 pytest.skip("")
-        """)
+        """
+        )
         reprec = testdir.inline_run(testpath, "--paste=failed")
         assert len(pastebinlist) == 1
         s = pastebinlist[0]
         assert s.find("def test_fail") != -1
         assert reprec.countoutcomes() == [1, 1, 1]
 
     def test_all(self, testdir, pastebinlist):
         from _pytest.pytester import LineMatcher
-        testpath = testdir.makepyfile("""
+
+        testpath = testdir.makepyfile(
+            """
             import pytest
             def test_pass():
                 pass
             def test_fail():
                 assert 0
             def test_skip():
                 pytest.skip("")
-        """)
-        reprec = testdir.inline_run(testpath, "--pastebin=all", '-v')
+        """
+        )
+        reprec = testdir.inline_run(testpath, "--pastebin=all", "-v")
         assert reprec.countoutcomes() == [1, 1, 1]
         assert len(pastebinlist) == 1
-        contents = pastebinlist[0].decode('utf-8')
+        contents = pastebinlist[0].decode("utf-8")
         matcher = LineMatcher(contents.splitlines())
-        matcher.fnmatch_lines([
-            '*test_pass PASSED*',
-            '*test_fail FAILED*',
-            '*test_skip SKIPPED*',
-            '*== 1 failed, 1 passed, 1 skipped in *'
-        ])
+        matcher.fnmatch_lines(
+            [
+                "*test_pass PASSED*",
+                "*test_fail FAILED*",
+                "*test_skip SKIPPED*",
+                "*== 1 failed, 1 passed, 1 skipped in *",
+            ]
+        )
 
     def test_non_ascii_paste_text(self, testdir):
         """Make sure that text which contains non-ascii characters is pasted
         correctly. See #1219.
         """
-        testdir.makepyfile(test_unicode="""
+        testdir.makepyfile(
+            test_unicode="""
             # encoding: utf-8
             def test():
                 assert '☺' == 1
-        """)
-        result = testdir.runpytest('--pastebin=all')
+        """
+        )
+        result = testdir.runpytest("--pastebin=all")
         if sys.version_info[0] == 3:
             expected_msg = "*assert '☺' == 1*"
         else:
             expected_msg = "*assert '\\xe2\\x98\\xba' == 1*"
-        result.stdout.fnmatch_lines([
-            expected_msg,
-            "*== 1 failed in *",
-            '*Sending information to Paste Service*',
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                expected_msg,
+                "*== 1 failed in *",
+                "*Sending information to Paste Service*",
+            ]
+        )
 
 
 class TestPaste(object):
 
     @pytest.fixture
     def pastebin(self, request):
-        return request.config.pluginmanager.getplugin('pastebin')
+        return request.config.pluginmanager.getplugin("pastebin")
 
     @pytest.fixture
     def mocked_urlopen(self, monkeypatch):
         """
         monkeypatch the actual urlopen calls done by the internal plugin
         function that connects to bpaste service.
         """
         calls = []
 
         def mocked(url, data):
             calls.append((url, data))
 
             class DummyFile(object):
+
                 def read(self):
                     # part of html of a normal response
                     return b'View <a href="/raw/3c0c6750bd">raw</a>.'
+
             return DummyFile()
 
         if sys.version_info < (3, 0):
             import urllib
-            monkeypatch.setattr(urllib, 'urlopen', mocked)
+
+            monkeypatch.setattr(urllib, "urlopen", mocked)
         else:
             import urllib.request
-            monkeypatch.setattr(urllib.request, 'urlopen', mocked)
+
+            monkeypatch.setattr(urllib.request, "urlopen", mocked)
         return calls
 
     def test_create_new_paste(self, pastebin, mocked_urlopen):
-        result = pastebin.create_new_paste(b'full-paste-contents')
-        assert result == 'https://bpaste.net/show/3c0c6750bd'
+        result = pastebin.create_new_paste(b"full-paste-contents")
+        assert result == "https://bpaste.net/show/3c0c6750bd"
         assert len(mocked_urlopen) == 1
         url, data = mocked_urlopen[0]
         assert type(data) is bytes
-        lexer = 'python3' if sys.version_info[0] == 3 else 'python'
-        assert url == 'https://bpaste.net'
-        assert 'lexer=%s' % lexer in data.decode()
-        assert 'code=full-paste-contents' in data.decode()
-        assert 'expiry=1week' in data.decode()
+        lexer = "python3" if sys.version_info[0] == 3 else "python"
+        assert url == "https://bpaste.net"
+        assert "lexer=%s" % lexer in data.decode()
+        assert "code=full-paste-contents" in data.decode()
+        assert "expiry=1week" in data.decode()
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_pdb.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_pdb.py
@@ -1,406 +1,702 @@
 from __future__ import absolute_import, division, print_function
 import sys
 import platform
+import os
 
 import _pytest._code
+from _pytest.debugging import SUPPORTS_BREAKPOINT_BUILTIN
 import pytest
 
 
+_ENVIRON_PYTHONBREAKPOINT = os.environ.get("PYTHONBREAKPOINT", "")
+
+
 def runpdb_and_get_report(testdir, source):
     p = testdir.makepyfile(source)
     result = testdir.runpytest_inprocess("--pdb", p)
     reports = result.reprec.getreports("pytest_runtest_logreport")
     assert len(reports) == 3, reports  # setup/call/teardown
     return reports[1]
 
 
 @pytest.fixture
 def custom_pdb_calls():
     called = []
 
     # install dummy debugger class and track which methods were called on it
     class _CustomPdb(object):
+
         def __init__(self, *args, **kwargs):
             called.append("init")
 
         def reset(self):
             called.append("reset")
 
         def interaction(self, *args):
             called.append("interaction")
 
     _pytest._CustomPdb = _CustomPdb
     return called
 
 
+@pytest.fixture
+def custom_debugger_hook():
+    called = []
+
+    # install dummy debugger class and track which methods were called on it
+    class _CustomDebugger(object):
+
+        def __init__(self, *args, **kwargs):
+            called.append("init")
+
+        def reset(self):
+            called.append("reset")
+
+        def interaction(self, *args):
+            called.append("interaction")
+
+        def set_trace(self, frame):
+            print("**CustomDebugger**")
+            called.append("set_trace")
+
+    _pytest._CustomDebugger = _CustomDebugger
+    yield called
+    del _pytest._CustomDebugger
+
+
 class TestPDB(object):
 
     @pytest.fixture
     def pdblist(self, request):
         monkeypatch = request.getfixturevalue("monkeypatch")
         pdblist = []
 
         def mypdb(*args):
             pdblist.append(args)
 
-        plugin = request.config.pluginmanager.getplugin('debugging')
-        monkeypatch.setattr(plugin, 'post_mortem', mypdb)
+        plugin = request.config.pluginmanager.getplugin("debugging")
+        monkeypatch.setattr(plugin, "post_mortem", mypdb)
         return pdblist
 
     def test_pdb_on_fail(self, testdir, pdblist):
-        rep = runpdb_and_get_report(testdir, """
+        rep = runpdb_and_get_report(
+            testdir,
+            """
             def test_func():
                 assert 0
-        """)
+        """,
+        )
         assert rep.failed
         assert len(pdblist) == 1
         tb = _pytest._code.Traceback(pdblist[0][0])
         assert tb[-1].name == "test_func"
 
     def test_pdb_on_xfail(self, testdir, pdblist):
-        rep = runpdb_and_get_report(testdir, """
+        rep = runpdb_and_get_report(
+            testdir,
+            """
             import pytest
             @pytest.mark.xfail
             def test_func():
                 assert 0
-        """)
+        """,
+        )
         assert "xfail" in rep.keywords
         assert not pdblist
 
     def test_pdb_on_skip(self, testdir, pdblist):
-        rep = runpdb_and_get_report(testdir, """
+        rep = runpdb_and_get_report(
+            testdir,
+            """
             import pytest
             def test_func():
                 pytest.skip("hello")
-        """)
+        """,
+        )
         assert rep.skipped
         assert len(pdblist) == 0
 
     def test_pdb_on_BdbQuit(self, testdir, pdblist):
-        rep = runpdb_and_get_report(testdir, """
+        rep = runpdb_and_get_report(
+            testdir,
+            """
             import bdb
             def test_func():
                 raise bdb.BdbQuit
-        """)
+        """,
+        )
         assert rep.failed
         assert len(pdblist) == 0
 
+    def test_pdb_on_KeyboardInterrupt(self, testdir, pdblist):
+        rep = runpdb_and_get_report(
+            testdir,
+            """
+            def test_func():
+                raise KeyboardInterrupt
+        """,
+        )
+        assert rep.failed
+        assert len(pdblist) == 1
+
     def test_pdb_interaction(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             def test_1():
                 i = 0
                 assert i == 1
-        """)
+        """
+        )
         child = testdir.spawn_pytest("--pdb %s" % p1)
         child.expect(".*def test_1")
         child.expect(".*i = 0")
         child.expect("(Pdb)")
         child.sendeof()
         rest = child.read().decode("utf8")
         assert "1 failed" in rest
         assert "def test_1" not in rest
         self.flush(child)
 
     @staticmethod
     def flush(child):
-        if platform.system() == 'Darwin':
+        if platform.system() == "Darwin":
             return
         if child.isalive():
             child.wait()
 
     def test_pdb_unittest_postmortem(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             import unittest
             class Blub(unittest.TestCase):
                 def tearDown(self):
                     self.filename = None
                 def test_false(self):
                     self.filename = 'debug' + '.me'
                     assert 0
-        """)
+        """
+        )
         child = testdir.spawn_pytest("--pdb %s" % p1)
-        child.expect('(Pdb)')
-        child.sendline('p self.filename')
+        child.expect("(Pdb)")
+        child.sendline("p self.filename")
         child.sendeof()
         rest = child.read().decode("utf8")
-        assert 'debug.me' in rest
+        assert "debug.me" in rest
         self.flush(child)
 
     def test_pdb_unittest_skip(self, testdir):
         """Test for issue #2137"""
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             import unittest
             @unittest.skipIf(True, 'Skipping also with pdb active')
             class MyTestCase(unittest.TestCase):
                 def test_one(self):
                     assert 0
-        """)
+        """
+        )
         child = testdir.spawn_pytest("-rs --pdb %s" % p1)
-        child.expect('Skipping also with pdb active')
-        child.expect('1 skipped in')
+        child.expect("Skipping also with pdb active")
+        child.expect("1 skipped in")
         child.sendeof()
         self.flush(child)
 
-    def test_pdb_interaction_capture(self, testdir):
-        p1 = testdir.makepyfile("""
+    def test_pdb_print_captured_stdout(self, testdir):
+        p1 = testdir.makepyfile(
+            """
             def test_1():
-                print("getrekt")
+                print("get\\x20rekt")
                 assert False
-        """)
+        """
+        )
         child = testdir.spawn_pytest("--pdb %s" % p1)
-        child.expect("getrekt")
+        child.expect("captured stdout")
+        child.expect("get rekt")
+        child.expect("(Pdb)")
+        child.sendeof()
+        rest = child.read().decode("utf8")
+        assert "1 failed" in rest
+        assert "get rekt" not in rest
+        self.flush(child)
+
+    def test_pdb_print_captured_stderr(self, testdir):
+        p1 = testdir.makepyfile(
+            """
+            def test_1():
+                import sys
+                sys.stderr.write("get\\x20rekt")
+                assert False
+        """
+        )
+        child = testdir.spawn_pytest("--pdb %s" % p1)
+        child.expect("captured stderr")
+        child.expect("get rekt")
         child.expect("(Pdb)")
         child.sendeof()
         rest = child.read().decode("utf8")
         assert "1 failed" in rest
-        assert "getrekt" not in rest
+        assert "get rekt" not in rest
+        self.flush(child)
+
+    def test_pdb_dont_print_empty_captured_stdout_and_stderr(self, testdir):
+        p1 = testdir.makepyfile(
+            """
+            def test_1():
+                assert False
+        """
+        )
+        child = testdir.spawn_pytest("--pdb %s" % p1)
+        child.expect("(Pdb)")
+        output = child.before.decode("utf8")
+        child.sendeof()
+        assert "captured stdout" not in output
+        assert "captured stderr" not in output
+        self.flush(child)
+
+    @pytest.mark.parametrize("showcapture", ["all", "no", "log"])
+    def test_pdb_print_captured_logs(self, testdir, showcapture):
+        p1 = testdir.makepyfile(
+            """
+            def test_1():
+                import logging
+                logging.warn("get " + "rekt")
+                assert False
+        """
+        )
+        child = testdir.spawn_pytest("--show-capture=%s --pdb %s" % (showcapture, p1))
+        if showcapture in ("all", "log"):
+            child.expect("captured log")
+            child.expect("get rekt")
+        child.expect("(Pdb)")
+        child.sendeof()
+        rest = child.read().decode("utf8")
+        assert "1 failed" in rest
+        self.flush(child)
+
+    def test_pdb_print_captured_logs_nologging(self, testdir):
+        p1 = testdir.makepyfile(
+            """
+            def test_1():
+                import logging
+                logging.warn("get " + "rekt")
+                assert False
+        """
+        )
+        child = testdir.spawn_pytest(
+            "--show-capture=all --pdb " "-p no:logging %s" % p1
+        )
+        child.expect("get rekt")
+        output = child.before.decode("utf8")
+        assert "captured log" not in output
+        child.expect("(Pdb)")
+        child.sendeof()
+        rest = child.read().decode("utf8")
+        assert "1 failed" in rest
         self.flush(child)
 
     def test_pdb_interaction_exception(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             import pytest
             def globalfunc():
                 pass
             def test_1():
                 pytest.raises(ValueError, globalfunc)
-        """)
+        """
+        )
         child = testdir.spawn_pytest("--pdb %s" % p1)
         child.expect(".*def test_1")
         child.expect(".*pytest.raises.*globalfunc")
         child.expect("(Pdb)")
         child.sendline("globalfunc")
         child.expect(".*function")
         child.sendeof()
         child.expect("1 failed")
         self.flush(child)
 
     def test_pdb_interaction_on_collection_issue181(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             import pytest
             xxx
-        """)
+        """
+        )
         child = testdir.spawn_pytest("--pdb %s" % p1)
         # child.expect(".*import pytest.*")
         child.expect("(Pdb)")
         child.sendeof()
         child.expect("1 error")
         self.flush(child)
 
     def test_pdb_interaction_on_internal_error(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_runtest_protocol():
                 0/0
-        """)
+        """
+        )
         p1 = testdir.makepyfile("def test_func(): pass")
         child = testdir.spawn_pytest("--pdb %s" % p1)
         # child.expect(".*import pytest.*")
         child.expect("(Pdb)")
         child.sendeof()
         self.flush(child)
 
     def test_pdb_interaction_capturing_simple(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             import pytest
             def test_1():
                 i = 0
                 print ("hello17")
                 pytest.set_trace()
                 x = 3
-        """)
+        """
+        )
         child = testdir.spawn_pytest(str(p1))
         child.expect("test_1")
         child.expect("x = 3")
         child.expect("(Pdb)")
         child.sendeof()
         rest = child.read().decode("utf-8")
         assert "1 failed" in rest
         assert "def test_1" in rest
         assert "hello17" in rest  # out is captured
         self.flush(child)
 
     def test_pdb_set_trace_interception(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             import pdb
             def test_1():
                 pdb.set_trace()
-        """)
+        """
+        )
         child = testdir.spawn_pytest(str(p1))
         child.expect("test_1")
         child.expect("(Pdb)")
         child.sendeof()
         rest = child.read().decode("utf8")
         assert "1 failed" in rest
         assert "reading from stdin while output" not in rest
         self.flush(child)
 
     def test_pdb_and_capsys(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             import pytest
             def test_1(capsys):
                 print ("hello1")
                 pytest.set_trace()
-        """)
+        """
+        )
         child = testdir.spawn_pytest(str(p1))
         child.expect("test_1")
         child.send("capsys.readouterr()\n")
         child.expect("hello1")
         child.sendeof()
         child.read()
         self.flush(child)
 
     def test_set_trace_capturing_afterwards(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             import pdb
             def test_1():
                 pdb.set_trace()
             def test_2():
                 print ("hello")
                 assert 0
-        """)
+        """
+        )
         child = testdir.spawn_pytest(str(p1))
         child.expect("test_1")
         child.send("c\n")
         child.expect("test_2")
         child.expect("Captured")
         child.expect("hello")
         child.sendeof()
         child.read()
         self.flush(child)
 
     def test_pdb_interaction_doctest(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             import pytest
             def function_1():
                 '''
                 >>> i = 0
                 >>> assert i == 1
                 '''
-        """)
+        """
+        )
         child = testdir.spawn_pytest("--doctest-modules --pdb %s" % p1)
         child.expect("(Pdb)")
-        child.sendline('i')
+        child.sendline("i")
         child.expect("0")
         child.expect("(Pdb)")
         child.sendeof()
         rest = child.read().decode("utf8")
         assert "1 failed" in rest
         self.flush(child)
 
     def test_pdb_interaction_capturing_twice(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             import pytest
             def test_1():
                 i = 0
                 print ("hello17")
                 pytest.set_trace()
                 x = 3
                 print ("hello18")
                 pytest.set_trace()
                 x = 4
-        """)
+        """
+        )
         child = testdir.spawn_pytest(str(p1))
         child.expect("test_1")
         child.expect("x = 3")
         child.expect("(Pdb)")
-        child.sendline('c')
+        child.sendline("c")
         child.expect("x = 4")
         child.sendeof()
         rest = child.read().decode("utf8")
         assert "1 failed" in rest
         assert "def test_1" in rest
         assert "hello17" in rest  # out is captured
         assert "hello18" in rest  # out is captured
         self.flush(child)
 
     def test_pdb_used_outside_test(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             import pytest
             pytest.set_trace()
             x = 5
-        """)
+        """
+        )
         child = testdir.spawn("%s %s" % (sys.executable, p1))
         child.expect("x = 5")
         child.sendeof()
         self.flush(child)
 
     def test_pdb_used_in_generate_tests(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             import pytest
             def pytest_generate_tests(metafunc):
                 pytest.set_trace()
                 x = 5
             def test_foo(a):
                 pass
-        """)
+        """
+        )
         child = testdir.spawn_pytest(str(p1))
         child.expect("x = 5")
         child.sendeof()
         self.flush(child)
 
     def test_pdb_collection_failure_is_shown(self, testdir):
-        p1 = testdir.makepyfile("""xxx """)
+        p1 = testdir.makepyfile("xxx")
         result = testdir.runpytest_subprocess("--pdb", p1)
-        result.stdout.fnmatch_lines([
-            "*NameError*xxx*",
-            "*1 error*",
-        ])
+        result.stdout.fnmatch_lines(["*NameError*xxx*", "*1 error*"])
 
     def test_enter_pdb_hook_is_called(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_enter_pdb(config):
                 assert config.testing_verification == 'configured'
                 print 'enter_pdb_hook'
 
             def pytest_configure(config):
                 config.testing_verification = 'configured'
-        """)
-        p1 = testdir.makepyfile("""
+        """
+        )
+        p1 = testdir.makepyfile(
+            """
             import pytest
 
             def test_foo():
                 pytest.set_trace()
-        """)
+        """
+        )
         child = testdir.spawn_pytest(str(p1))
         child.expect("enter_pdb_hook")
-        child.send('c\n')
+        child.send("c\n")
         child.sendeof()
         self.flush(child)
 
     def test_pdb_custom_cls(self, testdir, custom_pdb_calls):
         p1 = testdir.makepyfile("""xxx """)
-        result = testdir.runpytest_inprocess(
-            "--pdb", "--pdbcls=_pytest:_CustomPdb", p1)
-        result.stdout.fnmatch_lines([
-            "*NameError*xxx*",
-            "*1 error*",
-        ])
+        result = testdir.runpytest_inprocess("--pdb", "--pdbcls=_pytest:_CustomPdb", p1)
+        result.stdout.fnmatch_lines(["*NameError*xxx*", "*1 error*"])
         assert custom_pdb_calls == ["init", "reset", "interaction"]
 
     def test_pdb_custom_cls_without_pdb(self, testdir, custom_pdb_calls):
         p1 = testdir.makepyfile("""xxx """)
-        result = testdir.runpytest_inprocess(
-            "--pdbcls=_pytest:_CustomPdb", p1)
-        result.stdout.fnmatch_lines([
-            "*NameError*xxx*",
-            "*1 error*",
-        ])
+        result = testdir.runpytest_inprocess("--pdbcls=_pytest:_CustomPdb", p1)
+        result.stdout.fnmatch_lines(["*NameError*xxx*", "*1 error*"])
         assert custom_pdb_calls == []
 
     def test_pdb_custom_cls_with_settrace(self, testdir, monkeypatch):
-        testdir.makepyfile(custom_pdb="""
+        testdir.makepyfile(
+            custom_pdb="""
             class CustomPdb(object):
                 def set_trace(*args, **kwargs):
                     print 'custom set_trace>'
-         """)
-        p1 = testdir.makepyfile("""
+         """
+        )
+        p1 = testdir.makepyfile(
+            """
             import pytest
 
             def test_foo():
                 pytest.set_trace()
-        """)
-        monkeypatch.setenv('PYTHONPATH', str(testdir.tmpdir))
+        """
+        )
+        monkeypatch.setenv("PYTHONPATH", str(testdir.tmpdir))
         child = testdir.spawn_pytest("--pdbcls=custom_pdb:CustomPdb %s" % str(p1))
 
-        child.expect('custom set_trace>')
-        if child.isalive():
-            child.wait()
+        child.expect("custom set_trace>")
+        self.flush(child)
+
+
+class TestDebuggingBreakpoints(object):
+
+    def test_supports_breakpoint_module_global(self):
+        """
+        Test that supports breakpoint global marks on Python 3.7+ and not on
+        CPython 3.5, 2.7
+        """
+        if sys.version_info.major == 3 and sys.version_info.minor >= 7:
+            assert SUPPORTS_BREAKPOINT_BUILTIN is True
+        if sys.version_info.major == 3 and sys.version_info.minor == 5:
+            assert SUPPORTS_BREAKPOINT_BUILTIN is False
+        if sys.version_info.major == 2 and sys.version_info.minor == 7:
+            assert SUPPORTS_BREAKPOINT_BUILTIN is False
+
+    @pytest.mark.skipif(
+        not SUPPORTS_BREAKPOINT_BUILTIN, reason="Requires breakpoint() builtin"
+    )
+    @pytest.mark.parametrize("arg", ["--pdb", ""])
+    def test_sys_breakpointhook_configure_and_unconfigure(self, testdir, arg):
+        """
+        Test that sys.breakpointhook is set to the custom Pdb class once configured, test that
+        hook is reset to system value once pytest has been unconfigured
+        """
+        testdir.makeconftest(
+            """
+            import sys
+            from pytest import hookimpl
+            from _pytest.debugging import pytestPDB
+
+            def pytest_configure(config):
+                config._cleanup.append(check_restored)
+
+            def check_restored():
+                assert sys.breakpointhook == sys.__breakpointhook__
+
+            def test_check():
+                assert sys.breakpointhook == pytestPDB.set_trace
+        """
+        )
+        testdir.makepyfile(
+            """
+            def test_nothing(): pass
+        """
+        )
+        args = (arg,) if arg else ()
+        result = testdir.runpytest_subprocess(*args)
+        result.stdout.fnmatch_lines(["*1 passed in *"])
+
+    @pytest.mark.skipif(
+        not SUPPORTS_BREAKPOINT_BUILTIN, reason="Requires breakpoint() builtin"
+    )
+    def test_pdb_custom_cls(self, testdir, custom_debugger_hook):
+        p1 = testdir.makepyfile(
+            """
+            def test_nothing():
+                breakpoint()
+        """
+        )
+        result = testdir.runpytest_inprocess(
+            "--pdb", "--pdbcls=_pytest:_CustomDebugger", p1
+        )
+        result.stdout.fnmatch_lines(["*CustomDebugger*", "*1 passed*"])
+        assert custom_debugger_hook == ["init", "set_trace"]
+
+    @pytest.mark.parametrize("arg", ["--pdb", ""])
+    @pytest.mark.skipif(
+        not SUPPORTS_BREAKPOINT_BUILTIN, reason="Requires breakpoint() builtin"
+    )
+    def test_environ_custom_class(self, testdir, custom_debugger_hook, arg):
+        testdir.makeconftest(
+            """
+            import os
+            import sys
+
+            os.environ['PYTHONBREAKPOINT'] = '_pytest._CustomDebugger.set_trace'
+
+            def pytest_configure(config):
+                config._cleanup.append(check_restored)
+
+            def check_restored():
+                assert sys.breakpointhook == sys.__breakpointhook__
+
+            def test_check():
+                import _pytest
+                assert sys.breakpointhook is _pytest._CustomDebugger.set_trace
+        """
+        )
+        testdir.makepyfile(
+            """
+            def test_nothing(): pass
+        """
+        )
+        args = (arg,) if arg else ()
+        result = testdir.runpytest_subprocess(*args)
+        result.stdout.fnmatch_lines(["*1 passed in *"])
+
+    @pytest.mark.skipif(
+        not SUPPORTS_BREAKPOINT_BUILTIN, reason="Requires breakpoint() builtin"
+    )
+    @pytest.mark.skipif(
+        not _ENVIRON_PYTHONBREAKPOINT == "",
+        reason="Requires breakpoint() default value",
+    )
+    def test_sys_breakpoint_interception(self, testdir):
+        p1 = testdir.makepyfile(
+            """
+            def test_1():
+                breakpoint()
+        """
+        )
+        child = testdir.spawn_pytest(str(p1))
+        child.expect("test_1")
+        child.expect("(Pdb)")
+        child.sendeof()
+        rest = child.read().decode("utf8")
+        assert "1 failed" in rest
+        assert "reading from stdin while output" not in rest
+        TestPDB.flush(child)
+
+    @pytest.mark.skipif(
+        not SUPPORTS_BREAKPOINT_BUILTIN, reason="Requires breakpoint() builtin"
+    )
+    def test_pdb_not_altered(self, testdir):
+        p1 = testdir.makepyfile(
+            """
+            import pdb
+            def test_1():
+                pdb.set_trace()
+        """
+        )
+        child = testdir.spawn_pytest(str(p1))
+        child.expect("test_1")
+        child.expect("(Pdb)")
+        child.sendeof()
+        rest = child.read().decode("utf8")
+        assert "1 failed" in rest
+        assert "reading from stdin while output" not in rest
+        TestPDB.flush(child)
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_pluginmanager.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_pluginmanager.py
@@ -1,98 +1,115 @@
 # encoding: UTF-8
 from __future__ import absolute_import, division, print_function
 import pytest
-import py
 import os
+import re
+import sys
+import types
 
 from _pytest.config import get_config, PytestPluginManager
 from _pytest.main import EXIT_NOTESTSCOLLECTED, Session
 
 
 @pytest.fixture
 def pytestpm():
     return PytestPluginManager()
 
 
 class TestPytestPluginInteractions(object):
+
     def test_addhooks_conftestplugin(self, testdir):
-        testdir.makepyfile(newhooks="""
+        testdir.makepyfile(
+            newhooks="""
             def pytest_myhook(xyz):
                 "new hook"
-        """)
-        conf = testdir.makeconftest("""
+        """
+        )
+        conf = testdir.makeconftest(
+            """
             import sys ; sys.path.insert(0, '.')
             import newhooks
             def pytest_addhooks(pluginmanager):
                 pluginmanager.addhooks(newhooks)
             def pytest_myhook(xyz):
                 return xyz + 1
-        """)
+        """
+        )
         config = get_config()
         pm = config.pluginmanager
         pm.hook.pytest_addhooks.call_historic(
-            kwargs=dict(pluginmanager=config.pluginmanager))
+            kwargs=dict(pluginmanager=config.pluginmanager)
+        )
         config.pluginmanager._importconftest(conf)
         # print(config.pluginmanager.get_plugins())
         res = config.hook.pytest_myhook(xyz=10)
         assert res == [11]
 
     def test_addhooks_nohooks(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             import sys
             def pytest_addhooks(pluginmanager):
                 pluginmanager.addhooks(sys)
-        """)
+        """
+        )
         res = testdir.runpytest()
         assert res.ret != 0
-        res.stderr.fnmatch_lines([
-            "*did not find*sys*"
-        ])
+        res.stderr.fnmatch_lines(["*did not find*sys*"])
 
     def test_namespace_early_from_import(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             from pytest import Item
             from pytest import Item as Item2
             assert Item is Item2
-        """)
+        """
+        )
         result = testdir.runpython(p)
         assert result.ret == 0
 
     def test_do_ext_namespace(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_namespace():
                 return {'hello': 'world'}
-        """)
-        p = testdir.makepyfile("""
+        """
+        )
+        p = testdir.makepyfile(
+            """
             from pytest import hello
             import pytest
             def test_hello():
                 assert hello == "world"
                 assert 'hello' in pytest.__all__
-        """)
+        """
+        )
         reprec = testdir.inline_run(p)
         reprec.assertoutcome(passed=1)
 
     def test_do_option_postinitialize(self, testdir):
         config = testdir.parseconfigure()
-        assert not hasattr(config.option, 'test123')
-        p = testdir.makepyfile("""
+        assert not hasattr(config.option, "test123")
+        p = testdir.makepyfile(
+            """
             def pytest_addoption(parser):
                 parser.addoption('--test123', action="store_true",
                     default=True)
-        """)
+        """
+        )
         config.pluginmanager._importconftest(p)
         assert config.option.test123
 
     def test_configure(self, testdir):
         config = testdir.parseconfig()
         values = []
 
         class A(object):
+
             def pytest_configure(self, config):
                 values.append(self)
 
         config.pluginmanager.register(A())
         assert len(values) == 0
         config._do_configure()
         assert len(values) == 1
         config.pluginmanager.register(A())  # leads to a configured() plugin
@@ -103,209 +120,215 @@ class TestPytestPluginInteractions(objec
         config.pluginmanager.register(A())
         assert len(values) == 2
 
     def test_hook_tracing(self):
         pytestpm = get_config().pluginmanager  # fully initialized with plugins
         saveindent = []
 
         class api1(object):
+
             def pytest_plugin_registered(self):
                 saveindent.append(pytestpm.trace.root.indent)
 
         class api2(object):
+
             def pytest_plugin_registered(self):
                 saveindent.append(pytestpm.trace.root.indent)
                 raise ValueError()
 
         values = []
         pytestpm.trace.root.setwriter(values.append)
         undo = pytestpm.enable_tracing()
         try:
             indent = pytestpm.trace.root.indent
             p = api1()
             pytestpm.register(p)
             assert pytestpm.trace.root.indent == indent
             assert len(values) >= 2
-            assert 'pytest_plugin_registered' in values[0]
-            assert 'finish' in values[1]
+            assert "pytest_plugin_registered" in values[0]
+            assert "finish" in values[1]
 
             values[:] = []
             with pytest.raises(ValueError):
                 pytestpm.register(api2())
             assert pytestpm.trace.root.indent == indent
             assert saveindent[0] > indent
         finally:
             undo()
 
     def test_hook_proxy(self, testdir):
         """Test the gethookproxy function(#2016)"""
         config = testdir.parseconfig()
         session = Session(config)
-        testdir.makepyfile(**{
-            'tests/conftest.py': '',
-            'tests/subdir/conftest.py': '',
-        })
+        testdir.makepyfile(**{"tests/conftest.py": "", "tests/subdir/conftest.py": ""})
 
-        conftest1 = testdir.tmpdir.join('tests/conftest.py')
-        conftest2 = testdir.tmpdir.join('tests/subdir/conftest.py')
+        conftest1 = testdir.tmpdir.join("tests/conftest.py")
+        conftest2 = testdir.tmpdir.join("tests/subdir/conftest.py")
 
         config.pluginmanager._importconftest(conftest1)
-        ihook_a = session.gethookproxy(testdir.tmpdir.join('tests'))
+        ihook_a = session.gethookproxy(testdir.tmpdir.join("tests"))
         assert ihook_a is not None
         config.pluginmanager._importconftest(conftest2)
-        ihook_b = session.gethookproxy(testdir.tmpdir.join('tests'))
+        ihook_b = session.gethookproxy(testdir.tmpdir.join("tests"))
         assert ihook_a is not ihook_b
 
     def test_warn_on_deprecated_addhooks(self, pytestpm):
         warnings = []
 
         class get_warnings(object):
+
             def pytest_logwarning(self, code, fslocation, message, nodeid):
                 warnings.append(message)
 
         class Plugin(object):
+
             def pytest_testhook():
                 pass
 
         pytestpm.register(get_warnings())
         before = list(warnings)
         pytestpm.addhooks(Plugin())
         assert len(warnings) == len(before) + 1
         assert "deprecated" in warnings[-1]
 
 
 def test_namespace_has_default_and_env_plugins(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         import pytest
         pytest.mark
-    """)
+    """
+    )
     result = testdir.runpython(p)
     assert result.ret == 0
 
 
 def test_default_markers(testdir):
     result = testdir.runpytest("--markers")
-    result.stdout.fnmatch_lines([
-        "*tryfirst*first*",
-        "*trylast*last*",
-    ])
+    result.stdout.fnmatch_lines(["*tryfirst*first*", "*trylast*last*"])
 
 
 def test_importplugin_error_message(testdir, pytestpm):
     """Don't hide import errors when importing plugins and provide
     an easy to debug message.
 
     See #375 and #1998.
     """
     testdir.syspathinsert(testdir.tmpdir)
-    testdir.makepyfile(qwe="""
+    testdir.makepyfile(
+        qwe="""
         # encoding: UTF-8
         def test_traceback():
             raise ImportError(u'Not possible to import: ☺')
         test_traceback()
-    """)
+    """
+    )
     with pytest.raises(ImportError) as excinfo:
         pytestpm.import_plugin("qwe")
 
     expected_message = '.*Error importing plugin "qwe": Not possible to import: .'
     expected_traceback = ".*in test_traceback"
-    assert py.std.re.match(expected_message, str(excinfo.value))
-    assert py.std.re.match(expected_traceback, str(excinfo.traceback[-1]))
+    assert re.match(expected_message, str(excinfo.value))
+    assert re.match(expected_traceback, str(excinfo.traceback[-1]))
 
 
 class TestPytestPluginManager(object):
+
     def test_register_imported_modules(self):
         pm = PytestPluginManager()
-        mod = py.std.types.ModuleType("x.y.pytest_hello")
+        mod = types.ModuleType("x.y.pytest_hello")
         pm.register(mod)
         assert pm.is_registered(mod)
         values = pm.get_plugins()
         assert mod in values
         pytest.raises(ValueError, "pm.register(mod)")
         pytest.raises(ValueError, lambda: pm.register(mod))
         # assert not pm.is_registered(mod2)
         assert pm.get_plugins() == values
 
     def test_canonical_import(self, monkeypatch):
-        mod = py.std.types.ModuleType("pytest_xyz")
-        monkeypatch.setitem(py.std.sys.modules, 'pytest_xyz', mod)
+        mod = types.ModuleType("pytest_xyz")
+        monkeypatch.setitem(sys.modules, "pytest_xyz", mod)
         pm = PytestPluginManager()
-        pm.import_plugin('pytest_xyz')
-        assert pm.get_plugin('pytest_xyz') == mod
+        pm.import_plugin("pytest_xyz")
+        assert pm.get_plugin("pytest_xyz") == mod
         assert pm.is_registered(mod)
 
     def test_consider_module(self, testdir, pytestpm):
         testdir.syspathinsert()
         testdir.makepyfile(pytest_p1="#")
         testdir.makepyfile(pytest_p2="#")
-        mod = py.std.types.ModuleType("temp")
+        mod = types.ModuleType("temp")
         mod.pytest_plugins = ["pytest_p1", "pytest_p2"]
         pytestpm.consider_module(mod)
         assert pytestpm.get_plugin("pytest_p1").__name__ == "pytest_p1"
         assert pytestpm.get_plugin("pytest_p2").__name__ == "pytest_p2"
 
     def test_consider_module_import_module(self, testdir):
         pytestpm = get_config().pluginmanager
-        mod = py.std.types.ModuleType("x")
+        mod = types.ModuleType("x")
         mod.pytest_plugins = "pytest_a"
         aplugin = testdir.makepyfile(pytest_a="#")
         reprec = testdir.make_hook_recorder(pytestpm)
         # syspath.prepend(aplugin.dirpath())
-        py.std.sys.path.insert(0, str(aplugin.dirpath()))
+        sys.path.insert(0, str(aplugin.dirpath()))
         pytestpm.consider_module(mod)
         call = reprec.getcall(pytestpm.hook.pytest_plugin_registered.name)
         assert call.plugin.__name__ == "pytest_a"
 
         # check that it is not registered twice
         pytestpm.consider_module(mod)
         values = reprec.getcalls("pytest_plugin_registered")
         assert len(values) == 1
 
     def test_consider_env_fails_to_import(self, monkeypatch, pytestpm):
-        monkeypatch.setenv('PYTEST_PLUGINS', 'nonexisting', prepend=",")
+        monkeypatch.setenv("PYTEST_PLUGINS", "nonexisting", prepend=",")
         with pytest.raises(ImportError):
             pytestpm.consider_env()
 
     def test_plugin_skip(self, testdir, monkeypatch):
-        p = testdir.makepyfile(skipping1="""
+        p = testdir.makepyfile(
+            skipping1="""
             import pytest
             pytest.skip("hello")
-        """)
+        """
+        )
         p.copy(p.dirpath("skipping2.py"))
         monkeypatch.setenv("PYTEST_PLUGINS", "skipping2")
         result = testdir.runpytest("-rw", "-p", "skipping1", syspathinsert=True)
         assert result.ret == EXIT_NOTESTSCOLLECTED
-        result.stdout.fnmatch_lines([
-            "*skipped plugin*skipping1*hello*",
-            "*skipped plugin*skipping2*hello*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*skipped plugin*skipping1*hello*", "*skipped plugin*skipping2*hello*"]
+        )
 
     def test_consider_env_plugin_instantiation(self, testdir, monkeypatch, pytestpm):
         testdir.syspathinsert()
         testdir.makepyfile(xy123="#")
-        monkeypatch.setitem(os.environ, 'PYTEST_PLUGINS', 'xy123')
+        monkeypatch.setitem(os.environ, "PYTEST_PLUGINS", "xy123")
         l1 = len(pytestpm.get_plugins())
         pytestpm.consider_env()
         l2 = len(pytestpm.get_plugins())
         assert l2 == l1 + 1
-        assert pytestpm.get_plugin('xy123')
+        assert pytestpm.get_plugin("xy123")
         pytestpm.consider_env()
         l3 = len(pytestpm.get_plugins())
         assert l2 == l3
 
     def test_pluginmanager_ENV_startup(self, testdir, monkeypatch):
         testdir.makepyfile(pytest_x500="#")
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             def test_hello(pytestconfig):
                 plugin = pytestconfig.pluginmanager.get_plugin('pytest_x500')
                 assert plugin is not None
-        """)
-        monkeypatch.setenv('PYTEST_PLUGINS', 'pytest_x500', prepend=",")
+        """
+        )
+        monkeypatch.setenv("PYTEST_PLUGINS", "pytest_x500", prepend=",")
         result = testdir.runpytest(p, syspathinsert=True)
         assert result.ret == 0
         result.stdout.fnmatch_lines(["*1 passed*"])
 
     def test_import_plugin_importname(self, testdir, pytestpm):
         pytest.raises(ImportError, 'pytestpm.import_plugin("qweqwex.y")')
         pytest.raises(ImportError, 'pytestpm.import_plugin("pytest_qweqwx.y")')
 
@@ -313,17 +336,17 @@ class TestPytestPluginManager(object):
         pluginname = "pytest_hello"
         testdir.makepyfile(**{pluginname: ""})
         pytestpm.import_plugin("pytest_hello")
         len1 = len(pytestpm.get_plugins())
         pytestpm.import_plugin("pytest_hello")
         len2 = len(pytestpm.get_plugins())
         assert len1 == len2
         plugin1 = pytestpm.get_plugin("pytest_hello")
-        assert plugin1.__name__.endswith('pytest_hello')
+        assert plugin1.__name__.endswith("pytest_hello")
         plugin2 = pytestpm.get_plugin("pytest_hello")
         assert plugin2 is plugin1
 
     def test_import_plugin_dotted_name(self, testdir, pytestpm):
         pytest.raises(ImportError, 'pytestpm.import_plugin("qweqwex.y")')
         pytest.raises(ImportError, 'pytestpm.import_plugin("pytest_qweqwex.y")')
 
         testdir.syspathinsert()
@@ -335,19 +358,21 @@ class TestPytestPluginManager(object):
 
     def test_consider_conftest_deps(self, testdir, pytestpm):
         mod = testdir.makepyfile("pytest_plugins='xyz'").pyimport()
         with pytest.raises(ImportError):
             pytestpm.consider_conftest(mod)
 
 
 class TestPytestPluginManagerBootstrapming(object):
+
     def test_preparse_args(self, pytestpm):
-        pytest.raises(ImportError, lambda:
-                      pytestpm.consider_preparse(["xyz", "-p", "hello123"]))
+        pytest.raises(
+            ImportError, lambda: pytestpm.consider_preparse(["xyz", "-p", "hello123"])
+        )
 
     def test_plugin_prevent_register(self, pytestpm):
         pytestpm.consider_preparse(["xyz", "-p", "no:abc"])
         l1 = pytestpm.get_plugins()
         pytestpm.register(42, name="abc")
         l2 = pytestpm.get_plugins()
         assert len(l2) == len(l1)
         assert 42 not in l2
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_pytester.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_pytester.py
@@ -1,13 +1,17 @@
 # -*- coding: utf-8 -*-
 from __future__ import absolute_import, division, print_function
+import os
+import py.path
 import pytest
-import os
+import sys
+import _pytest.pytester as pytester
 from _pytest.pytester import HookRecorder
+from _pytest.pytester import CwdSnapshot, SysModulesSnapshot, SysPathsSnapshot
 from _pytest.config import PytestPluginManager
 from _pytest.main import EXIT_OK, EXIT_TESTSFAILED
 
 
 def test_make_hook_recorder(testdir):
     item = testdir.getitem("def test_func(): pass")
     recorder = testdir.make_hook_recorder(item.config.pluginmanager)
     assert not recorder.getfailures()
@@ -28,16 +32,17 @@ def test_make_hook_recorder(testdir):
     assert failures == [rep]
 
     class rep(object):
         excinfo = None
         passed = False
         failed = False
         skipped = True
         when = "call"
+
     rep.passed = False
     rep.skipped = True
     recorder.hook.pytest_runtest_logreport(report=rep)
 
     modcol = testdir.getmodulecol("")
     rep = modcol.config.hook.pytest_make_collect_report(collector=modcol)
     rep.passed = False
     rep.failed = True
@@ -62,34 +67,38 @@ def test_make_hook_recorder(testdir):
 def test_parseconfig(testdir):
     config1 = testdir.parseconfig()
     config2 = testdir.parseconfig()
     assert config2 != config1
     assert config1 != pytest.config
 
 
 def test_testdir_runs_with_plugin(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         pytest_plugins = "pytester"
         def test_hello(testdir):
             assert 1
-    """)
+    """
+    )
     result = testdir.runpytest()
     result.assert_outcomes(passed=1)
 
 
 def make_holder():
+
     class apiclass(object):
+
         def pytest_xyz(self, arg):
             "x"
 
         def pytest_xyz_noarg(self):
             "x"
 
-    apimod = type(os)('api')
+    apimod = type(os)("api")
 
     def pytest_xyz(arg):
         "x"
 
     def pytest_xyz_noarg():
         "x"
 
     apimod.pytest_xyz = pytest_xyz
@@ -121,29 +130,272 @@ def test_makepyfile_unicode(testdir):
     testdir.makepyfile(unichr(0xfffd))
 
 
 def test_makepyfile_utf8(testdir):
     """Ensure makepyfile accepts utf-8 bytes as input (#2738)"""
     utf8_contents = u"""
         def setup_function(function):
             mixed_encoding = u'São Paulo'
-    """.encode('utf-8')
+    """.encode(
+        "utf-8"
+    )
     p = testdir.makepyfile(utf8_contents)
-    assert u"mixed_encoding = u'São Paulo'".encode('utf-8') in p.read('rb')
+    assert u"mixed_encoding = u'São Paulo'".encode("utf-8") in p.read("rb")
+
+
+class TestInlineRunModulesCleanup(object):
+
+    def test_inline_run_test_module_not_cleaned_up(self, testdir):
+        test_mod = testdir.makepyfile("def test_foo(): assert True")
+        result = testdir.inline_run(str(test_mod))
+        assert result.ret == EXIT_OK
+        # rewrite module, now test should fail if module was re-imported
+        test_mod.write("def test_foo(): assert False")
+        result2 = testdir.inline_run(str(test_mod))
+        assert result2.ret == EXIT_TESTSFAILED
+
+    def spy_factory(self):
+
+        class SysModulesSnapshotSpy(object):
+            instances = []
+
+            def __init__(self, preserve=None):
+                SysModulesSnapshotSpy.instances.append(self)
+                self._spy_restore_count = 0
+                self._spy_preserve = preserve
+                self.__snapshot = SysModulesSnapshot(preserve=preserve)
+
+            def restore(self):
+                self._spy_restore_count += 1
+                return self.__snapshot.restore()
+
+        return SysModulesSnapshotSpy
+
+    def test_inline_run_taking_and_restoring_a_sys_modules_snapshot(
+        self, testdir, monkeypatch
+    ):
+        spy_factory = self.spy_factory()
+        monkeypatch.setattr(pytester, "SysModulesSnapshot", spy_factory)
+        original = dict(sys.modules)
+        testdir.syspathinsert()
+        testdir.makepyfile(import1="# you son of a silly person")
+        testdir.makepyfile(import2="# my hovercraft is full of eels")
+        test_mod = testdir.makepyfile(
+            """
+            import import1
+            def test_foo(): import import2"""
+        )
+        testdir.inline_run(str(test_mod))
+        assert len(spy_factory.instances) == 1
+        spy = spy_factory.instances[0]
+        assert spy._spy_restore_count == 1
+        assert sys.modules == original
+        assert all(sys.modules[x] is original[x] for x in sys.modules)
+
+    def test_inline_run_sys_modules_snapshot_restore_preserving_modules(
+        self, testdir, monkeypatch
+    ):
+        spy_factory = self.spy_factory()
+        monkeypatch.setattr(pytester, "SysModulesSnapshot", spy_factory)
+        test_mod = testdir.makepyfile("def test_foo(): pass")
+        testdir.inline_run(str(test_mod))
+        spy = spy_factory.instances[0]
+        assert not spy._spy_preserve("black_knight")
+        assert spy._spy_preserve("zope")
+        assert spy._spy_preserve("zope.interface")
+        assert spy._spy_preserve("zopelicious")
+
+    def test_external_test_module_imports_not_cleaned_up(self, testdir):
+        testdir.syspathinsert()
+        testdir.makepyfile(imported="data = 'you son of a silly person'")
+        import imported
+
+        test_mod = testdir.makepyfile(
+            """
+            def test_foo():
+                import imported
+                imported.data = 42"""
+        )
+        testdir.inline_run(str(test_mod))
+        assert imported.data == 42
 
 
-def test_inline_run_clean_modules(testdir):
-    test_mod = testdir.makepyfile("def test_foo(): assert True")
-    result = testdir.inline_run(str(test_mod))
-    assert result.ret == EXIT_OK
-    # rewrite module, now test should fail if module was re-imported
-    test_mod.write("def test_foo(): assert False")
-    result2 = testdir.inline_run(str(test_mod))
-    assert result2.ret == EXIT_TESTSFAILED
+def test_inline_run_clean_sys_paths(testdir):
+
+    def test_sys_path_change_cleanup(self, testdir):
+        test_path1 = testdir.tmpdir.join("boink1").strpath
+        test_path2 = testdir.tmpdir.join("boink2").strpath
+        test_path3 = testdir.tmpdir.join("boink3").strpath
+        sys.path.append(test_path1)
+        sys.meta_path.append(test_path1)
+        original_path = list(sys.path)
+        original_meta_path = list(sys.meta_path)
+        test_mod = testdir.makepyfile(
+            """
+            import sys
+            sys.path.append({:test_path2})
+            sys.meta_path.append({:test_path2})
+            def test_foo():
+                sys.path.append({:test_path3})
+                sys.meta_path.append({:test_path3})""".format(
+                locals()
+            )
+        )
+        testdir.inline_run(str(test_mod))
+        assert sys.path == original_path
+        assert sys.meta_path == original_meta_path
+
+    def spy_factory(self):
+
+        class SysPathsSnapshotSpy(object):
+            instances = []
+
+            def __init__(self):
+                SysPathsSnapshotSpy.instances.append(self)
+                self._spy_restore_count = 0
+                self.__snapshot = SysPathsSnapshot()
+
+            def restore(self):
+                self._spy_restore_count += 1
+                return self.__snapshot.restore()
+
+        return SysPathsSnapshotSpy
+
+    def test_inline_run_taking_and_restoring_a_sys_paths_snapshot(
+        self, testdir, monkeypatch
+    ):
+        spy_factory = self.spy_factory()
+        monkeypatch.setattr(pytester, "SysPathsSnapshot", spy_factory)
+        test_mod = testdir.makepyfile("def test_foo(): pass")
+        testdir.inline_run(str(test_mod))
+        assert len(spy_factory.instances) == 1
+        spy = spy_factory.instances[0]
+        assert spy._spy_restore_count == 1
+
+
+def test_assert_outcomes_after_pytest_error(testdir):
+    testdir.makepyfile("def test_foo(): assert True")
+
+    result = testdir.runpytest("--unexpected-argument")
+    with pytest.raises(ValueError, message="Pytest terminal report not found"):
+        result.assert_outcomes(passed=0)
+
+
+def test_cwd_snapshot(tmpdir):
+    foo = tmpdir.ensure("foo", dir=1)
+    bar = tmpdir.ensure("bar", dir=1)
+    foo.chdir()
+    snapshot = CwdSnapshot()
+    bar.chdir()
+    assert py.path.local() == bar
+    snapshot.restore()
+    assert py.path.local() == foo
 
 
-def test_assert_outcomes_after_pytest_erro(testdir):
-    testdir.makepyfile("def test_foo(): assert True")
+class TestSysModulesSnapshot(object):
+    key = "my-test-module"
+
+    def test_remove_added(self):
+        original = dict(sys.modules)
+        assert self.key not in sys.modules
+        snapshot = SysModulesSnapshot()
+        sys.modules[self.key] = "something"
+        assert self.key in sys.modules
+        snapshot.restore()
+        assert sys.modules == original
+
+    def test_add_removed(self, monkeypatch):
+        assert self.key not in sys.modules
+        monkeypatch.setitem(sys.modules, self.key, "something")
+        assert self.key in sys.modules
+        original = dict(sys.modules)
+        snapshot = SysModulesSnapshot()
+        del sys.modules[self.key]
+        assert self.key not in sys.modules
+        snapshot.restore()
+        assert sys.modules == original
+
+    def test_restore_reloaded(self, monkeypatch):
+        assert self.key not in sys.modules
+        monkeypatch.setitem(sys.modules, self.key, "something")
+        assert self.key in sys.modules
+        original = dict(sys.modules)
+        snapshot = SysModulesSnapshot()
+        sys.modules[self.key] = "something else"
+        snapshot.restore()
+        assert sys.modules == original
+
+    def test_preserve_modules(self, monkeypatch):
+        key = [self.key + str(i) for i in range(3)]
+        assert not any(k in sys.modules for k in key)
+        for i, k in enumerate(key):
+            monkeypatch.setitem(sys.modules, k, "something" + str(i))
+        original = dict(sys.modules)
+
+        def preserve(name):
+            return name in (key[0], key[1], "some-other-key")
+
+        snapshot = SysModulesSnapshot(preserve=preserve)
+        sys.modules[key[0]] = original[key[0]] = "something else0"
+        sys.modules[key[1]] = original[key[1]] = "something else1"
+        sys.modules[key[2]] = "something else2"
+        snapshot.restore()
+        assert sys.modules == original
 
-    result = testdir.runpytest('--unexpected-argument')
-    with pytest.raises(ValueError, message="Pytest terminal report not found"):
-        result.assert_outcomes(passed=0)
+    def test_preserve_container(self, monkeypatch):
+        original = dict(sys.modules)
+        assert self.key not in original
+        replacement = dict(sys.modules)
+        replacement[self.key] = "life of brian"
+        snapshot = SysModulesSnapshot()
+        monkeypatch.setattr(sys, "modules", replacement)
+        snapshot.restore()
+        assert sys.modules is replacement
+        assert sys.modules == original
+
+
+@pytest.mark.parametrize("path_type", ("path", "meta_path"))
+class TestSysPathsSnapshot(object):
+    other_path = {"path": "meta_path", "meta_path": "path"}
+
+    @staticmethod
+    def path(n):
+        return "my-dirty-little-secret-" + str(n)
+
+    def test_restore(self, monkeypatch, path_type):
+        other_path_type = self.other_path[path_type]
+        for i in range(10):
+            assert self.path(i) not in getattr(sys, path_type)
+        sys_path = [self.path(i) for i in range(6)]
+        monkeypatch.setattr(sys, path_type, sys_path)
+        original = list(sys_path)
+        original_other = list(getattr(sys, other_path_type))
+        snapshot = SysPathsSnapshot()
+        transformation = {
+            "source": (0, 1, 2, 3, 4, 5), "target": (6, 2, 9, 7, 5, 8)
+        }  # noqa: E201
+        assert sys_path == [self.path(x) for x in transformation["source"]]
+        sys_path[1] = self.path(6)
+        sys_path[3] = self.path(7)
+        sys_path.append(self.path(8))
+        del sys_path[4]
+        sys_path[3:3] = [self.path(9)]
+        del sys_path[0]
+        assert sys_path == [self.path(x) for x in transformation["target"]]
+        snapshot.restore()
+        assert getattr(sys, path_type) is sys_path
+        assert getattr(sys, path_type) == original
+        assert getattr(sys, other_path_type) == original_other
+
+    def test_preserve_container(self, monkeypatch, path_type):
+        other_path_type = self.other_path[path_type]
+        original_data = list(getattr(sys, path_type))
+        original_other = getattr(sys, other_path_type)
+        original_other_data = list(original_other)
+        new = []
+        snapshot = SysPathsSnapshot()
+        monkeypatch.setattr(sys, path_type, new)
+        snapshot.restore()
+        assert getattr(sys, path_type) is new
+        assert getattr(sys, path_type) == original_data
+        assert getattr(sys, other_path_type) is original_other
+        assert getattr(sys, other_path_type) == original_other_data
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_recwarn.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_recwarn.py
@@ -1,52 +1,55 @@
 from __future__ import absolute_import, division, print_function
 import warnings
 import re
-import py
 
 import pytest
 from _pytest.recwarn import WarningsRecorder
 
 
 def test_recwarn_functional(testdir):
-    reprec = testdir.inline_runsource("""
+    reprec = testdir.inline_runsource(
+        """
         import warnings
         def test_method(recwarn):
             warnings.warn("hello")
             warn = recwarn.pop()
             assert isinstance(warn.message, UserWarning)
-    """)
+    """
+    )
     res = reprec.countoutcomes()
     assert tuple(res) == (1, 0, 0), res
 
 
 class TestWarningsRecorderChecker(object):
+
     def test_recording(self):
         rec = WarningsRecorder()
         with rec:
             assert not rec.list
-            py.std.warnings.warn_explicit("hello", UserWarning, "xyz", 13)
+            warnings.warn_explicit("hello", UserWarning, "xyz", 13)
             assert len(rec.list) == 1
-            py.std.warnings.warn(DeprecationWarning("hello"))
+            warnings.warn(DeprecationWarning("hello"))
             assert len(rec.list) == 2
             warn = rec.pop()
             assert str(warn.message) == "hello"
             values = rec.list
             rec.clear()
             assert len(rec.list) == 0
             assert values is rec.list
             pytest.raises(AssertionError, "rec.pop()")
 
     def test_typechecking(self):
         from _pytest.recwarn import WarningsChecker
+
         with pytest.raises(TypeError):
             WarningsChecker(5)
         with pytest.raises(TypeError):
-            WarningsChecker(('hi', RuntimeWarning))
+            WarningsChecker(("hi", RuntimeWarning))
         with pytest.raises(TypeError):
             WarningsChecker([DeprecationWarning, RuntimeWarning])
 
     def test_invalid_enter_exit(self):
         # wrap this test in WarningsRecorder to ensure warning state gets reset
         with WarningsRecorder():
             with pytest.raises(RuntimeError):
                 rec = WarningsRecorder()
@@ -59,183 +62,215 @@ class TestWarningsRecorderChecker(object
                         pass  # can't enter twice
 
 
 class TestDeprecatedCall(object):
     """test pytest.deprecated_call()"""
 
     def dep(self, i, j=None):
         if i == 0:
-            py.std.warnings.warn("is deprecated", DeprecationWarning,
-                                 stacklevel=1)
+            warnings.warn("is deprecated", DeprecationWarning, stacklevel=1)
         return 42
 
     def dep_explicit(self, i):
         if i == 0:
-            py.std.warnings.warn_explicit("dep_explicit", category=DeprecationWarning,
-                                          filename="hello", lineno=3)
+            warnings.warn_explicit(
+                "dep_explicit", category=DeprecationWarning, filename="hello", lineno=3
+            )
 
     def test_deprecated_call_raises(self):
         with pytest.raises(AssertionError) as excinfo:
             pytest.deprecated_call(self.dep, 3, 5)
-        assert 'Did not produce' in str(excinfo)
+        assert "Did not produce" in str(excinfo)
 
     def test_deprecated_call(self):
         pytest.deprecated_call(self.dep, 0, 5)
 
     def test_deprecated_call_ret(self):
         ret = pytest.deprecated_call(self.dep, 0)
         assert ret == 42
 
     def test_deprecated_call_preserves(self):
-        onceregistry = py.std.warnings.onceregistry.copy()
-        filters = py.std.warnings.filters[:]
-        warn = py.std.warnings.warn
-        warn_explicit = py.std.warnings.warn_explicit
+        onceregistry = warnings.onceregistry.copy()
+        filters = warnings.filters[:]
+        warn = warnings.warn
+        warn_explicit = warnings.warn_explicit
         self.test_deprecated_call_raises()
         self.test_deprecated_call()
-        assert onceregistry == py.std.warnings.onceregistry
-        assert filters == py.std.warnings.filters
-        assert warn is py.std.warnings.warn
-        assert warn_explicit is py.std.warnings.warn_explicit
+        assert onceregistry == warnings.onceregistry
+        assert filters == warnings.filters
+        assert warn is warnings.warn
+        assert warn_explicit is warnings.warn_explicit
 
     def test_deprecated_explicit_call_raises(self):
         with pytest.raises(AssertionError):
             pytest.deprecated_call(self.dep_explicit, 3)
 
     def test_deprecated_explicit_call(self):
         pytest.deprecated_call(self.dep_explicit, 0)
         pytest.deprecated_call(self.dep_explicit, 0)
 
-    @pytest.mark.parametrize('mode', ['context_manager', 'call'])
+    @pytest.mark.parametrize("mode", ["context_manager", "call"])
     def test_deprecated_call_no_warning(self, mode):
         """Ensure deprecated_call() raises the expected failure when its block/function does
         not raise a deprecation warning.
         """
+
         def f():
             pass
 
-        msg = 'Did not produce DeprecationWarning or PendingDeprecationWarning'
-        with pytest.raises(AssertionError, matches=msg):
-            if mode == 'call':
+        msg = "Did not produce DeprecationWarning or PendingDeprecationWarning"
+        with pytest.raises(AssertionError, match=msg):
+            if mode == "call":
                 pytest.deprecated_call(f)
             else:
                 with pytest.deprecated_call():
                     f()
 
-    @pytest.mark.parametrize('warning_type', [PendingDeprecationWarning, DeprecationWarning])
-    @pytest.mark.parametrize('mode', ['context_manager', 'call'])
-    @pytest.mark.parametrize('call_f_first', [True, False])
-    @pytest.mark.filterwarnings('ignore')
+    @pytest.mark.parametrize(
+        "warning_type", [PendingDeprecationWarning, DeprecationWarning]
+    )
+    @pytest.mark.parametrize("mode", ["context_manager", "call"])
+    @pytest.mark.parametrize("call_f_first", [True, False])
+    @pytest.mark.filterwarnings("ignore")
     def test_deprecated_call_modes(self, warning_type, mode, call_f_first):
         """Ensure deprecated_call() captures a deprecation warning as expected inside its
         block/function.
         """
+
         def f():
             warnings.warn(warning_type("hi"))
             return 10
 
         # ensure deprecated_call() can capture the warning even if it has already been triggered
         if call_f_first:
             assert f() == 10
-        if mode == 'call':
+        if mode == "call":
             assert pytest.deprecated_call(f) == 10
         else:
             with pytest.deprecated_call():
                 assert f() == 10
 
-    @pytest.mark.parametrize('mode', ['context_manager', 'call'])
+    @pytest.mark.parametrize("mode", ["context_manager", "call"])
     def test_deprecated_call_exception_is_raised(self, mode):
         """If the block of the code being tested by deprecated_call() raises an exception,
         it must raise the exception undisturbed.
         """
-        def f():
-            raise ValueError('some exception')
 
-        with pytest.raises(ValueError, match='some exception'):
-            if mode == 'call':
+        def f():
+            raise ValueError("some exception")
+
+        with pytest.raises(ValueError, match="some exception"):
+            if mode == "call":
                 pytest.deprecated_call(f)
             else:
                 with pytest.deprecated_call():
                     f()
 
     def test_deprecated_call_specificity(self):
-        other_warnings = [Warning, UserWarning, SyntaxWarning, RuntimeWarning,
-                          FutureWarning, ImportWarning, UnicodeWarning]
+        other_warnings = [
+            Warning,
+            UserWarning,
+            SyntaxWarning,
+            RuntimeWarning,
+            FutureWarning,
+            ImportWarning,
+            UnicodeWarning,
+        ]
         for warning in other_warnings:
+
             def f():
                 warnings.warn(warning("hi"))
 
             with pytest.raises(AssertionError):
                 pytest.deprecated_call(f)
             with pytest.raises(AssertionError):
                 with pytest.deprecated_call():
                     f()
 
 
 class TestWarns(object):
+
     def test_strings(self):
         # different messages, b/c Python suppresses multiple identical warnings
         source1 = "warnings.warn('w1', RuntimeWarning)"
         source2 = "warnings.warn('w2', RuntimeWarning)"
         source3 = "warnings.warn('w3', RuntimeWarning)"
         pytest.warns(RuntimeWarning, source1)
-        pytest.raises(pytest.fail.Exception,
-                      lambda: pytest.warns(UserWarning, source2))
+        pytest.raises(pytest.fail.Exception, lambda: pytest.warns(UserWarning, source2))
         pytest.warns(RuntimeWarning, source3)
 
     def test_function(self):
-        pytest.warns(SyntaxWarning,
-                     lambda msg: warnings.warn(msg, SyntaxWarning), "syntax")
+        pytest.warns(
+            SyntaxWarning, lambda msg: warnings.warn(msg, SyntaxWarning), "syntax"
+        )
 
     def test_warning_tuple(self):
-        pytest.warns((RuntimeWarning, SyntaxWarning),
-                     lambda: warnings.warn('w1', RuntimeWarning))
-        pytest.warns((RuntimeWarning, SyntaxWarning),
-                     lambda: warnings.warn('w2', SyntaxWarning))
-        pytest.raises(pytest.fail.Exception,
-                      lambda: pytest.warns(
-                          (RuntimeWarning, SyntaxWarning),
-                          lambda: warnings.warn('w3', UserWarning)))
+        pytest.warns(
+            (RuntimeWarning, SyntaxWarning), lambda: warnings.warn("w1", RuntimeWarning)
+        )
+        pytest.warns(
+            (RuntimeWarning, SyntaxWarning), lambda: warnings.warn("w2", SyntaxWarning)
+        )
+        pytest.raises(
+            pytest.fail.Exception,
+            lambda: pytest.warns(
+                (RuntimeWarning, SyntaxWarning),
+                lambda: warnings.warn("w3", UserWarning),
+            ),
+        )
 
     def test_as_contextmanager(self):
         with pytest.warns(RuntimeWarning):
             warnings.warn("runtime", RuntimeWarning)
 
         with pytest.warns(UserWarning):
             warnings.warn("user", UserWarning)
 
         with pytest.raises(pytest.fail.Exception) as excinfo:
             with pytest.warns(RuntimeWarning):
                 warnings.warn("user", UserWarning)
-        excinfo.match(r"DID NOT WARN. No warnings of type \(.+RuntimeWarning.+,\) was emitted. "
-                      r"The list of emitted warnings is: \[UserWarning\('user',\)\].")
+        excinfo.match(
+            r"DID NOT WARN. No warnings of type \(.+RuntimeWarning.+,\) was emitted. "
+            r"The list of emitted warnings is: \[UserWarning\('user',?\)\]."
+        )
 
         with pytest.raises(pytest.fail.Exception) as excinfo:
             with pytest.warns(UserWarning):
                 warnings.warn("runtime", RuntimeWarning)
-        excinfo.match(r"DID NOT WARN. No warnings of type \(.+UserWarning.+,\) was emitted. "
-                      r"The list of emitted warnings is: \[RuntimeWarning\('runtime',\)\].")
+        excinfo.match(
+            r"DID NOT WARN. No warnings of type \(.+UserWarning.+,\) was emitted. "
+            r"The list of emitted warnings is: \[RuntimeWarning\('runtime',?\)\]."
+        )
 
         with pytest.raises(pytest.fail.Exception) as excinfo:
             with pytest.warns(UserWarning):
                 pass
-        excinfo.match(r"DID NOT WARN. No warnings of type \(.+UserWarning.+,\) was emitted. "
-                      r"The list of emitted warnings is: \[\].")
+        excinfo.match(
+            r"DID NOT WARN. No warnings of type \(.+UserWarning.+,\) was emitted. "
+            r"The list of emitted warnings is: \[\]."
+        )
 
         warning_classes = (UserWarning, FutureWarning)
         with pytest.raises(pytest.fail.Exception) as excinfo:
             with pytest.warns(warning_classes) as warninfo:
                 warnings.warn("runtime", RuntimeWarning)
                 warnings.warn("import", ImportWarning)
 
-        message_template = ("DID NOT WARN. No warnings of type {0} was emitted. "
-                            "The list of emitted warnings is: {1}.")
-        excinfo.match(re.escape(message_template.format(warning_classes,
-                                                        [each.message for each in warninfo])))
+        message_template = (
+            "DID NOT WARN. No warnings of type {0} was emitted. "
+            "The list of emitted warnings is: {1}."
+        )
+        excinfo.match(
+            re.escape(
+                message_template.format(
+                    warning_classes, [each.message for each in warninfo]
+                )
+            )
+        )
 
     def test_record(self):
         with pytest.warns(UserWarning) as record:
             warnings.warn("user", UserWarning)
 
         assert len(record) == 1
         assert str(record[0].message) == "user"
 
@@ -268,43 +303,45 @@ class TestWarns(object):
             warnings.warn("runtime", MyRuntimeWarning)
 
         assert len(record) == 2
         assert str(record[0].message) == "user"
         assert str(record[1].message) == "runtime"
 
     def test_double_test(self, testdir):
         """If a test is run again, the warning should still be raised"""
-        testdir.makepyfile('''
+        testdir.makepyfile(
+            """
             import pytest
             import warnings
 
             @pytest.mark.parametrize('run', [1, 2])
             def test(run):
                 with pytest.warns(RuntimeWarning):
                     warnings.warn("runtime", RuntimeWarning)
-        ''')
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines(['*2 passed in*'])
+        result.stdout.fnmatch_lines(["*2 passed in*"])
 
     def test_match_regex(self):
-        with pytest.warns(UserWarning, match=r'must be \d+$'):
+        with pytest.warns(UserWarning, match=r"must be \d+$"):
             warnings.warn("value must be 42", UserWarning)
 
         with pytest.raises(pytest.fail.Exception):
-            with pytest.warns(UserWarning, match=r'must be \d+$'):
+            with pytest.warns(UserWarning, match=r"must be \d+$"):
                 warnings.warn("this is not here", UserWarning)
 
         with pytest.raises(pytest.fail.Exception):
-            with pytest.warns(FutureWarning, match=r'must be \d+$'):
+            with pytest.warns(FutureWarning, match=r"must be \d+$"):
                 warnings.warn("value must be 42", UserWarning)
 
     def test_one_from_multiple_warns(self):
-        with pytest.warns(UserWarning, match=r'aaa'):
+        with pytest.warns(UserWarning, match=r"aaa"):
             warnings.warn("cccccccccc", UserWarning)
             warnings.warn("bbbbbbbbbb", UserWarning)
             warnings.warn("aaaaaaaaaa", UserWarning)
 
     def test_none_of_multiple_warns(self):
         with pytest.raises(pytest.fail.Exception):
-            with pytest.warns(UserWarning, match=r'aaa'):
+            with pytest.warns(UserWarning, match=r"aaa"):
                 warnings.warn("bbbbbbbbbb", UserWarning)
                 warnings.warn("cccccccccc", UserWarning)
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_resultlog.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_resultlog.py
@@ -1,80 +1,85 @@
 from __future__ import absolute_import, division, print_function
 import os
 
 import _pytest._code
 import py
 import pytest
-from _pytest.main import Node, Item, FSCollector
-from _pytest.resultlog import generic_path, ResultLog, \
-    pytest_configure, pytest_unconfigure
+from _pytest.nodes import Node, Item, FSCollector
+from _pytest.resultlog import (
+    generic_path,
+    ResultLog,
+    pytest_configure,
+    pytest_unconfigure,
+)
 
 
 def test_generic_path(testdir):
     from _pytest.main import Session
+
     config = testdir.parseconfig()
     session = Session(config)
-    p1 = Node('a', config=config, session=session)
+    p1 = Node("a", config=config, session=session, nodeid="a")
     # assert p1.fspath is None
-    p2 = Node('B', parent=p1)
-    p3 = Node('()', parent=p2)
-    item = Item('c', parent=p3)
+    p2 = Node("B", parent=p1)
+    p3 = Node("()", parent=p2)
+    item = Item("c", parent=p3)
 
     res = generic_path(item)
-    assert res == 'a.B().c'
+    assert res == "a.B().c"
 
-    p0 = FSCollector('proj/test', config=config, session=session)
-    p1 = FSCollector('proj/test/a', parent=p0)
-    p2 = Node('B', parent=p1)
-    p3 = Node('()', parent=p2)
-    p4 = Node('c', parent=p3)
-    item = Item('[1]', parent=p4)
+    p0 = FSCollector("proj/test", config=config, session=session)
+    p1 = FSCollector("proj/test/a", parent=p0)
+    p2 = Node("B", parent=p1)
+    p3 = Node("()", parent=p2)
+    p4 = Node("c", parent=p3)
+    item = Item("[1]", parent=p4)
 
     res = generic_path(item)
-    assert res == 'test/a:B().c[1]'
+    assert res == "test/a:B().c[1]"
 
 
 def test_write_log_entry():
     reslog = ResultLog(None, None)
     reslog.logfile = py.io.TextIO()
-    reslog.write_log_entry('name', '.', '')
+    reslog.write_log_entry("name", ".", "")
     entry = reslog.logfile.getvalue()
-    assert entry[-1] == '\n'
+    assert entry[-1] == "\n"
     entry_lines = entry.splitlines()
     assert len(entry_lines) == 1
-    assert entry_lines[0] == '. name'
+    assert entry_lines[0] == ". name"
 
     reslog.logfile = py.io.TextIO()
-    reslog.write_log_entry('name', 's', 'Skipped')
+    reslog.write_log_entry("name", "s", "Skipped")
     entry = reslog.logfile.getvalue()
-    assert entry[-1] == '\n'
+    assert entry[-1] == "\n"
     entry_lines = entry.splitlines()
     assert len(entry_lines) == 2
-    assert entry_lines[0] == 's name'
-    assert entry_lines[1] == ' Skipped'
+    assert entry_lines[0] == "s name"
+    assert entry_lines[1] == " Skipped"
 
     reslog.logfile = py.io.TextIO()
-    reslog.write_log_entry('name', 's', 'Skipped\n')
+    reslog.write_log_entry("name", "s", "Skipped\n")
     entry = reslog.logfile.getvalue()
-    assert entry[-1] == '\n'
+    assert entry[-1] == "\n"
     entry_lines = entry.splitlines()
     assert len(entry_lines) == 2
-    assert entry_lines[0] == 's name'
-    assert entry_lines[1] == ' Skipped'
+    assert entry_lines[0] == "s name"
+    assert entry_lines[1] == " Skipped"
 
     reslog.logfile = py.io.TextIO()
-    longrepr = ' tb1\n tb 2\nE tb3\nSome Error'
-    reslog.write_log_entry('name', 'F', longrepr)
+    longrepr = " tb1\n tb 2\nE tb3\nSome Error"
+    reslog.write_log_entry("name", "F", longrepr)
     entry = reslog.logfile.getvalue()
-    assert entry[-1] == '\n'
+    assert entry[-1] == "\n"
     entry_lines = entry.splitlines()
     assert len(entry_lines) == 5
-    assert entry_lines[0] == 'F name'
-    assert entry_lines[1:] == [' ' + line for line in longrepr.splitlines()]
+    assert entry_lines[0] == "F name"
+    assert entry_lines[1:] == [" " + line for line in longrepr.splitlines()]
 
 
 class TestWithFunctionIntegration(object):
     # XXX (hpk) i think that the resultlog plugin should
     # provide a Parser object so that one can remain
     # ignorant regarding formatting details.
     def getresultlog(self, testdir, arg):
         resultlog = testdir.tmpdir.join("resultlog")
@@ -93,136 +98,146 @@ class TestWithFunctionIntegration(object
         assert lines
         assert lines[0].startswith("F ")
         assert lines[0].endswith("test_collection_fail.py"), lines[0]
         for x in lines[1:]:
             assert x.startswith(" ")
         assert "XXX" in "".join(lines[1:])
 
     def test_log_test_outcomes(self, testdir):
-        mod = testdir.makepyfile(test_mod="""
+        mod = testdir.makepyfile(
+            test_mod="""
             import pytest
             def test_pass(): pass
             def test_skip(): pytest.skip("hello")
             def test_fail(): raise ValueError("FAIL")
 
             @pytest.mark.xfail
             def test_xfail(): raise ValueError("XFAIL")
             @pytest.mark.xfail
             def test_xpass(): pass
 
-        """)
+        """
+        )
         lines = self.getresultlog(testdir, mod)
         assert len(lines) >= 3
         assert lines[0].startswith(". ")
         assert lines[0].endswith("test_pass")
         assert lines[1].startswith("s "), lines[1]
         assert lines[1].endswith("test_skip")
         assert lines[2].find("hello") != -1
 
         assert lines[3].startswith("F ")
         assert lines[3].endswith("test_fail")
         tb = "".join(lines[4:8])
         assert tb.find('raise ValueError("FAIL")') != -1
 
-        assert lines[8].startswith('x ')
+        assert lines[8].startswith("x ")
         tb = "".join(lines[8:14])
         assert tb.find('raise ValueError("XFAIL")') != -1
 
-        assert lines[14].startswith('X ')
+        assert lines[14].startswith("X ")
         assert len(lines) == 15
 
     @pytest.mark.parametrize("style", ("native", "long", "short"))
     def test_internal_exception(self, style):
         # they are produced for example by a teardown failing
         # at the end of the run or a failing hook invocation
         try:
             raise ValueError
         except ValueError:
             excinfo = _pytest._code.ExceptionInfo()
         reslog = ResultLog(None, py.io.TextIO())
         reslog.pytest_internalerror(excinfo.getrepr(style=style))
         entry = reslog.logfile.getvalue()
         entry_lines = entry.splitlines()
 
-        assert entry_lines[0].startswith('! ')
+        assert entry_lines[0].startswith("! ")
         if style != "native":
             assert os.path.basename(__file__)[:-9] in entry_lines[0]  # .pyc/class
-        assert entry_lines[-1][0] == ' '
-        assert 'ValueError' in entry
+        assert entry_lines[-1][0] == " "
+        assert "ValueError" in entry
 
 
 def test_generic(testdir, LineMatcher):
     testdir.plugins.append("resultlog")
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         def test_pass():
             pass
         def test_fail():
             assert 0
         def test_skip():
             pytest.skip("")
         @pytest.mark.xfail
         def test_xfail():
             assert 0
         @pytest.mark.xfail(run=False)
         def test_xfail_norun():
             assert 0
-    """)
+    """
+    )
     testdir.runpytest("--resultlog=result.log")
     lines = testdir.tmpdir.join("result.log").readlines(cr=0)
-    LineMatcher(lines).fnmatch_lines([
-        ". *:test_pass",
-        "F *:test_fail",
-        "s *:test_skip",
-        "x *:test_xfail",
-        "x *:test_xfail_norun",
-    ])
+    LineMatcher(lines).fnmatch_lines(
+        [
+            ". *:test_pass",
+            "F *:test_fail",
+            "s *:test_skip",
+            "x *:test_xfail",
+            "x *:test_xfail_norun",
+        ]
+    )
 
 
 def test_makedir_for_resultlog(testdir, LineMatcher):
     """--resultlog should automatically create directories for the log file"""
     testdir.plugins.append("resultlog")
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         def test_pass():
             pass
-    """)
+    """
+    )
     testdir.runpytest("--resultlog=path/to/result.log")
     lines = testdir.tmpdir.join("path/to/result.log").readlines(cr=0)
-    LineMatcher(lines).fnmatch_lines([
-        ". *:test_pass",
-    ])
+    LineMatcher(lines).fnmatch_lines([". *:test_pass"])
 
 
 def test_no_resultlog_on_slaves(testdir):
     config = testdir.parseconfig("-p", "resultlog", "--resultlog=resultlog")
 
-    assert not hasattr(config, '_resultlog')
+    assert not hasattr(config, "_resultlog")
     pytest_configure(config)
-    assert hasattr(config, '_resultlog')
+    assert hasattr(config, "_resultlog")
     pytest_unconfigure(config)
-    assert not hasattr(config, '_resultlog')
+    assert not hasattr(config, "_resultlog")
 
     config.slaveinput = {}
     pytest_configure(config)
-    assert not hasattr(config, '_resultlog')
+    assert not hasattr(config, "_resultlog")
     pytest_unconfigure(config)
-    assert not hasattr(config, '_resultlog')
+    assert not hasattr(config, "_resultlog")
 
 
 def test_failure_issue380(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         import pytest
         class MyCollector(pytest.File):
             def collect(self):
                 raise ValueError()
             def repr_failure(self, excinfo):
                 return "somestring"
         def pytest_collect_file(path, parent):
             return MyCollector(parent=parent, fspath=path)
-    """)
-    testdir.makepyfile("""
+    """
+    )
+    testdir.makepyfile(
+        """
         def test_func():
             pass
-    """)
+    """
+    )
     result = testdir.runpytest("--resultlog=log")
     assert result.ret == 2
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_runner.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_runner.py
@@ -1,20 +1,23 @@
 # -*- coding: utf-8 -*-
 from __future__ import absolute_import, division, print_function
 
 import _pytest._code
+import inspect
 import os
 import py
 import pytest
 import sys
+import types
 from _pytest import runner, main, outcomes
 
 
 class TestSetupState(object):
+
     def test_setup(self, testdir):
         ss = runner.SetupState()
         item = testdir.getitem("def test_func(): pass")
         values = [1]
         ss.prepare(item)
         ss.addfinalizer(values.pop, colitem=item)
         assert values
         ss._pop_and_teardown()
@@ -23,192 +26,249 @@ class TestSetupState(object):
     def test_teardown_exact_stack_empty(self, testdir):
         item = testdir.getitem("def test_func(): pass")
         ss = runner.SetupState()
         ss.teardown_exact(item, None)
         ss.teardown_exact(item, None)
         ss.teardown_exact(item, None)
 
     def test_setup_fails_and_failure_is_cached(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             def setup_module(mod):
                 raise ValueError(42)
             def test_func(): pass
-        """)  # noqa
+        """
+        )
         ss = runner.SetupState()
         pytest.raises(ValueError, lambda: ss.prepare(item))
         pytest.raises(ValueError, lambda: ss.prepare(item))
 
     def test_teardown_multiple_one_fails(self, testdir):
         r = []
 
         def fin1():
-            r.append('fin1')
+            r.append("fin1")
 
         def fin2():
-            raise Exception('oops')
+            raise Exception("oops")
 
         def fin3():
-            r.append('fin3')
+            r.append("fin3")
 
         item = testdir.getitem("def test_func(): pass")
         ss = runner.SetupState()
         ss.addfinalizer(fin1, item)
         ss.addfinalizer(fin2, item)
         ss.addfinalizer(fin3, item)
         with pytest.raises(Exception) as err:
             ss._callfinalizers(item)
-        assert err.value.args == ('oops',)
-        assert r == ['fin3', 'fin1']
+        assert err.value.args == ("oops",)
+        assert r == ["fin3", "fin1"]
 
     def test_teardown_multiple_fail(self, testdir):
         # Ensure the first exception is the one which is re-raised.
         # Ideally both would be reported however.
         def fin1():
-            raise Exception('oops1')
+            raise Exception("oops1")
 
         def fin2():
-            raise Exception('oops2')
+            raise Exception("oops2")
 
         item = testdir.getitem("def test_func(): pass")
         ss = runner.SetupState()
         ss.addfinalizer(fin1, item)
         ss.addfinalizer(fin2, item)
         with pytest.raises(Exception) as err:
             ss._callfinalizers(item)
-        assert err.value.args == ('oops2',)
+        assert err.value.args == ("oops2",)
+
+    def test_teardown_multiple_scopes_one_fails(self, testdir):
+        module_teardown = []
+
+        def fin_func():
+            raise Exception("oops1")
+
+        def fin_module():
+            module_teardown.append("fin_module")
+
+        item = testdir.getitem("def test_func(): pass")
+        ss = runner.SetupState()
+        ss.addfinalizer(fin_module, item.listchain()[-2])
+        ss.addfinalizer(fin_func, item)
+        ss.prepare(item)
+        with pytest.raises(Exception, match="oops1"):
+            ss.teardown_exact(item, None)
+        assert module_teardown
 
 
 class BaseFunctionalTests(object):
+
     def test_passfunction(self, testdir):
-        reports = testdir.runitem("""
+        reports = testdir.runitem(
+            """
             def test_func():
                 pass
-        """)
+        """
+        )
         rep = reports[1]
         assert rep.passed
         assert not rep.failed
         assert rep.outcome == "passed"
         assert not rep.longrepr
 
     def test_failfunction(self, testdir):
-        reports = testdir.runitem("""
+        reports = testdir.runitem(
+            """
             def test_func():
                 assert 0
-        """)
+        """
+        )
         rep = reports[1]
         assert not rep.passed
         assert not rep.skipped
         assert rep.failed
         assert rep.when == "call"
         assert rep.outcome == "failed"
         # assert isinstance(rep.longrepr, ReprExceptionInfo)
 
     def test_skipfunction(self, testdir):
-        reports = testdir.runitem("""
+        reports = testdir.runitem(
+            """
             import pytest
             def test_func():
                 pytest.skip("hello")
-        """)
+        """
+        )
         rep = reports[1]
         assert not rep.failed
         assert not rep.passed
         assert rep.skipped
         assert rep.outcome == "skipped"
         # assert rep.skipped.when == "call"
         # assert rep.skipped.when == "call"
         # assert rep.skipped == "%sreason == "hello"
         # assert rep.skipped.location.lineno == 3
         # assert rep.skipped.location.path
         # assert not rep.skipped.failurerepr
 
     def test_skip_in_setup_function(self, testdir):
-        reports = testdir.runitem("""
+        reports = testdir.runitem(
+            """
             import pytest
             def setup_function(func):
                 pytest.skip("hello")
             def test_func():
                 pass
-        """)
+        """
+        )
         print(reports)
         rep = reports[0]
         assert not rep.failed
         assert not rep.passed
         assert rep.skipped
         # assert rep.skipped.reason == "hello"
         # assert rep.skipped.location.lineno == 3
         # assert rep.skipped.location.lineno == 3
         assert len(reports) == 2
         assert reports[1].passed  # teardown
 
     def test_failure_in_setup_function(self, testdir):
-        reports = testdir.runitem("""
+        reports = testdir.runitem(
+            """
             import pytest
             def setup_function(func):
                 raise ValueError(42)
             def test_func():
                 pass
-        """)
+        """
+        )
         rep = reports[0]
         assert not rep.skipped
         assert not rep.passed
         assert rep.failed
         assert rep.when == "setup"
         assert len(reports) == 2
 
     def test_failure_in_teardown_function(self, testdir):
-        reports = testdir.runitem("""
+        reports = testdir.runitem(
+            """
             import pytest
             def teardown_function(func):
                 raise ValueError(42)
             def test_func():
                 pass
-        """)
+        """
+        )
         print(reports)
         assert len(reports) == 3
         rep = reports[2]
         assert not rep.skipped
         assert not rep.passed
         assert rep.failed
         assert rep.when == "teardown"
         # assert rep.longrepr.reprcrash.lineno == 3
         # assert rep.longrepr.reprtraceback.reprentries
 
     def test_custom_failure_repr(self, testdir):
-        testdir.makepyfile(conftest="""
+        testdir.makepyfile(
+            conftest="""
             import pytest
             class Function(pytest.Function):
                 def repr_failure(self, excinfo):
                     return "hello"
-        """)
-        reports = testdir.runitem("""
+        """
+        )
+        reports = testdir.runitem(
+            """
             import pytest
             def test_func():
                 assert 0
-        """)
+        """
+        )
         rep = reports[1]
         assert not rep.skipped
         assert not rep.passed
         assert rep.failed
         # assert rep.outcome.when == "call"
         # assert rep.failed.where.lineno == 3
         # assert rep.failed.where.path.basename == "test_func.py"
         # assert rep.failed.failurerepr == "hello"
 
     def test_teardown_final_returncode(self, testdir):
-        rec = testdir.inline_runsource("""
+        rec = testdir.inline_runsource(
+            """
             def test_func():
                 pass
             def teardown_function(func):
                 raise ValueError(42)
-        """)
+        """
+        )
         assert rec.ret == 1
 
+    def test_logstart_logfinish_hooks(self, testdir):
+        rec = testdir.inline_runsource(
+            """
+            import pytest
+            def test_func():
+                pass
+        """
+        )
+        reps = rec.getcalls("pytest_runtest_logstart pytest_runtest_logfinish")
+        assert (
+            [x._name for x in reps]
+            == ["pytest_runtest_logstart", "pytest_runtest_logfinish"]
+        )
+        for rep in reps:
+            assert rep.nodeid == "test_logstart_logfinish_hooks.py::test_func"
+            assert rep.location == ("test_logstart_logfinish_hooks.py", 1, "test_func")
+
     def test_exact_teardown_issue90(self, testdir):
-        rec = testdir.inline_runsource("""
+        rec = testdir.inline_runsource(
+            """
             import pytest
 
             class TestClass(object):
                 def test_method(self):
                     pass
                 def teardown_class(cls):
                     raise Exception()
 
@@ -219,17 +279,18 @@ class BaseFunctionalTests(object):
                 # sys.exc_info would return the indexerror
                 # from guessing the lastitem
                 excinfo = sys.exc_info()
                 import traceback
                 assert excinfo[0] is None, \
                        traceback.format_exception(*excinfo)
             def teardown_function(func):
                 raise ValueError(42)
-        """)
+        """
+        )
         reps = rec.getreports("pytest_runtest_logreport")
         print(reps)
         for i in range(2):
             assert reps[i].nodeid.endswith("test_method")
             assert reps[i].passed
         assert reps[2].when == "teardown"
         assert reps[2].failed
         assert len(reps) == 6
@@ -237,142 +298,162 @@ class BaseFunctionalTests(object):
             assert reps[i].nodeid.endswith("test_func")
             assert reps[i].passed
         assert reps[5].when == "teardown"
         assert reps[5].nodeid.endswith("test_func")
         assert reps[5].failed
 
     def test_exact_teardown_issue1206(self, testdir):
         """issue shadowing error with wrong number of arguments on teardown_method."""
-        rec = testdir.inline_runsource("""
+        rec = testdir.inline_runsource(
+            """
             import pytest
 
             class TestClass(object):
                 def teardown_method(self, x, y, z):
                     pass
 
                 def test_method(self):
                     assert True
-        """)
+        """
+        )
         reps = rec.getreports("pytest_runtest_logreport")
         print(reps)
         assert len(reps) == 3
         #
         assert reps[0].nodeid.endswith("test_method")
         assert reps[0].passed
-        assert reps[0].when == 'setup'
+        assert reps[0].when == "setup"
         #
         assert reps[1].nodeid.endswith("test_method")
         assert reps[1].passed
-        assert reps[1].when == 'call'
+        assert reps[1].when == "call"
         #
         assert reps[2].nodeid.endswith("test_method")
         assert reps[2].failed
         assert reps[2].when == "teardown"
         assert reps[2].longrepr.reprcrash.message in (
             # python3 error
             "TypeError: teardown_method() missing 2 required positional arguments: 'y' and 'z'",
             # python2 error
-            'TypeError: teardown_method() takes exactly 4 arguments (2 given)'
+            "TypeError: teardown_method() takes exactly 4 arguments (2 given)",
         )
 
     def test_failure_in_setup_function_ignores_custom_repr(self, testdir):
-        testdir.makepyfile(conftest="""
+        testdir.makepyfile(
+            conftest="""
             import pytest
             class Function(pytest.Function):
                 def repr_failure(self, excinfo):
                     assert 0
-        """)
-        reports = testdir.runitem("""
+        """
+        )
+        reports = testdir.runitem(
+            """
             def setup_function(func):
                 raise ValueError(42)
             def test_func():
                 pass
-        """)
+        """
+        )
         assert len(reports) == 2
         rep = reports[0]
         print(rep)
         assert not rep.skipped
         assert not rep.passed
         assert rep.failed
         # assert rep.outcome.when == "setup"
         # assert rep.outcome.where.lineno == 3
         # assert rep.outcome.where.path.basename == "test_func.py"
         # assert instanace(rep.failed.failurerepr, PythonFailureRepr)
 
     def test_systemexit_does_not_bail_out(self, testdir):
         try:
-            reports = testdir.runitem("""
+            reports = testdir.runitem(
+                """
                 def test_func():
                     raise SystemExit(42)
-            """)
+            """
+            )
         except SystemExit:
             pytest.fail("runner did not catch SystemExit")
         rep = reports[1]
         assert rep.failed
         assert rep.when == "call"
 
     def test_exit_propagates(self, testdir):
         try:
-            testdir.runitem("""
+            testdir.runitem(
+                """
                 import pytest
                 def test_func():
                     raise pytest.exit.Exception()
-            """)
+            """
+            )
         except pytest.exit.Exception:
             pass
         else:
             pytest.fail("did not raise")
 
 
 class TestExecutionNonForked(BaseFunctionalTests):
+
     def getrunner(self):
+
         def f(item):
             return runner.runtestprotocol(item, log=False)
+
         return f
 
     def test_keyboardinterrupt_propagates(self, testdir):
         try:
-            testdir.runitem("""
+            testdir.runitem(
+                """
                 def test_func():
                     raise KeyboardInterrupt("fake")
-            """)
+            """
+            )
         except KeyboardInterrupt:
             pass
         else:
             pytest.fail("did not raise")
 
 
 class TestExecutionForked(BaseFunctionalTests):
     pytestmark = pytest.mark.skipif("not hasattr(os, 'fork')")
 
     def getrunner(self):
         # XXX re-arrange this test to live in pytest-xdist
         boxed = pytest.importorskip("xdist.boxed")
         return boxed.forked_run_report
 
     def test_suicide(self, testdir):
-        reports = testdir.runitem("""
+        reports = testdir.runitem(
+            """
             def test_func():
                 import os
                 os.kill(os.getpid(), 15)
-        """)
+        """
+        )
         rep = reports[0]
         assert rep.failed
         assert rep.when == "???"
 
 
 class TestSessionReports(object):
+
     def test_collect_result(self, testdir):
-        col = testdir.getmodulecol("""
+        col = testdir.getmodulecol(
+            """
             def test_func1():
                 pass
             class TestClass(object):
                 pass
-        """)
+        """
+        )
         rep = runner.collect_one_node(col)
         assert not rep.failed
         assert not rep.skipped
         assert rep.passed
         locinfo = rep.location
         assert locinfo[0] == col.fspath.basename
         assert not locinfo[1]
         assert locinfo[2] == col.fspath.basename
@@ -385,45 +466,49 @@ class TestSessionReports(object):
 reporttypes = [
     runner.BaseReport,
     runner.TestReport,
     runner.TeardownErrorReport,
     runner.CollectReport,
 ]
 
 
-@pytest.mark.parametrize('reporttype', reporttypes, ids=[x.__name__ for x in reporttypes])
+@pytest.mark.parametrize(
+    "reporttype", reporttypes, ids=[x.__name__ for x in reporttypes]
+)
 def test_report_extra_parameters(reporttype):
-    if hasattr(py.std.inspect, 'signature'):
-        args = list(py.std.inspect.signature(reporttype.__init__).parameters.keys())[1:]
+    if hasattr(inspect, "signature"):
+        args = list(inspect.signature(reporttype.__init__).parameters.keys())[1:]
     else:
-        args = py.std.inspect.getargspec(reporttype.__init__)[0][1:]
+        args = inspect.getargspec(reporttype.__init__)[0][1:]
     basekw = dict.fromkeys(args, [])
     report = reporttype(newthing=1, **basekw)
     assert report.newthing == 1
 
 
 def test_callinfo():
-    ci = runner.CallInfo(lambda: 0, '123')
+    ci = runner.CallInfo(lambda: 0, "123")
     assert ci.when == "123"
     assert ci.result == 0
     assert "result" in repr(ci)
-    ci = runner.CallInfo(lambda: 0 / 0, '123')
+    ci = runner.CallInfo(lambda: 0 / 0, "123")
     assert ci.when == "123"
-    assert not hasattr(ci, 'result')
+    assert not hasattr(ci, "result")
     assert ci.excinfo
     assert "exc" in repr(ci)
 
+
 # design question: do we want general hooks in python files?
 # then something like the following functional tests makes sense
 
 
 @pytest.mark.xfail
 def test_runtest_in_module_ordering(testdir):
-    p1 = testdir.makepyfile("""
+    p1 = testdir.makepyfile(
+        """
         import pytest
         def pytest_runtest_setup(item): # runs after class-level!
             item.function.mylist.append("module")
         class TestClass(object):
             def pytest_runtest_setup(self, item):
                 assert not hasattr(item.function, 'mylist')
                 item.function.mylist = ['class']
             @pytest.fixture
@@ -436,32 +521,31 @@ def test_runtest_in_module_ordering(test
                     pass
             def test_hello1(self, mylist):
                 assert mylist == ['class', 'module'], mylist
                 raise ValueError()
             def test_hello2(self, mylist):
                 assert mylist == ['class', 'module'], mylist
         def pytest_runtest_teardown(item):
             del item.function.mylist
-    """)
+    """
+    )
     result = testdir.runpytest(p1)
-    result.stdout.fnmatch_lines([
-        "*2 passed*"
-    ])
+    result.stdout.fnmatch_lines(["*2 passed*"])
 
 
 def test_outcomeexception_exceptionattributes():
-    outcome = outcomes.OutcomeException('test')
+    outcome = outcomes.OutcomeException("test")
     assert outcome.args[0] == outcome.msg
 
 
 def test_outcomeexception_passes_except_Exception():
     with pytest.raises(outcomes.OutcomeException):
         try:
-            raise outcomes.OutcomeException('test')
+            raise outcomes.OutcomeException("test")
         except Exception:
             pass
 
 
 def test_pytest_exit():
     try:
         pytest.exit("hello")
     except pytest.exit.Exception:
@@ -474,82 +558,86 @@ def test_pytest_fail():
         pytest.fail("hello")
     except pytest.fail.Exception:
         excinfo = _pytest._code.ExceptionInfo()
         s = excinfo.exconly(tryshort=True)
         assert s.startswith("Failed")
 
 
 def test_pytest_exit_msg(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
     import pytest
 
     def pytest_configure(config):
         pytest.exit('oh noes')
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stderr.fnmatch_lines([
-        "Exit: oh noes",
-    ])
+    result.stderr.fnmatch_lines(["Exit: oh noes"])
 
 
 def test_pytest_fail_notrace(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         def test_hello():
             pytest.fail("hello", pytrace=False)
         def teardown_function(function):
             pytest.fail("world", pytrace=False)
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        "world",
-        "hello",
-    ])
-    assert 'def teardown_function' not in result.stdout.str()
+    result.stdout.fnmatch_lines(["world", "hello"])
+    assert "def teardown_function" not in result.stdout.str()
 
 
-@pytest.mark.parametrize('str_prefix', ['u', ''])
+@pytest.mark.parametrize("str_prefix", ["u", ""])
 def test_pytest_fail_notrace_non_ascii(testdir, str_prefix):
     """Fix pytest.fail with pytrace=False with non-ascii characters (#1178).
 
     This tests with native and unicode strings containing non-ascii chars.
     """
-    testdir.makepyfile(u"""
+    testdir.makepyfile(
+        u"""
         # coding: utf-8
         import pytest
 
         def test_hello():
             pytest.fail(%s'oh oh: ☺', pytrace=False)
-    """ % str_prefix)
+    """
+        % str_prefix
+    )
     result = testdir.runpytest()
     if sys.version_info[0] >= 3:
-        result.stdout.fnmatch_lines(['*test_hello*', "oh oh: ☺"])
+        result.stdout.fnmatch_lines(["*test_hello*", "oh oh: ☺"])
     else:
-        result.stdout.fnmatch_lines(['*test_hello*', "oh oh: *"])
-    assert 'def test_hello' not in result.stdout.str()
+        result.stdout.fnmatch_lines(["*test_hello*", "oh oh: *"])
+    assert "def test_hello" not in result.stdout.str()
 
 
 def test_pytest_no_tests_collected_exit_status(testdir):
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines('*collected 0 items*')
+    result.stdout.fnmatch_lines("*collected 0 items*")
     assert result.ret == main.EXIT_NOTESTSCOLLECTED
 
-    testdir.makepyfile(test_foo="""
+    testdir.makepyfile(
+        test_foo="""
         def test_foo():
             assert 1
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines('*collected 1 item*')
-    result.stdout.fnmatch_lines('*1 passed*')
+    result.stdout.fnmatch_lines("*collected 1 item*")
+    result.stdout.fnmatch_lines("*1 passed*")
     assert result.ret == main.EXIT_OK
 
-    result = testdir.runpytest('-k nonmatch')
-    result.stdout.fnmatch_lines('*collected 1 item*')
-    result.stdout.fnmatch_lines('*1 deselected*')
+    result = testdir.runpytest("-k nonmatch")
+    result.stdout.fnmatch_lines("*collected 1 item*")
+    result.stdout.fnmatch_lines("*1 deselected*")
     assert result.ret == main.EXIT_NOTESTSCOLLECTED
 
 
 def test_exception_printing_skip():
     try:
         pytest.skip("hello")
     except pytest.skip.Exception:
         excinfo = _pytest._code.ExceptionInfo()
@@ -559,255 +647,305 @@ def test_exception_printing_skip():
 
 def test_importorskip(monkeypatch):
     importorskip = pytest.importorskip
 
     def f():
         importorskip("asdlkj")
 
     try:
-        sys = importorskip("sys")  # noqa
-        assert sys == py.std.sys
+        sysmod = importorskip("sys")
+        assert sysmod is sys
         # path = pytest.importorskip("os.path")
-        # assert path == py.std.os.path
+        # assert path == os.path
         excinfo = pytest.raises(pytest.skip.Exception, f)
         path = py.path.local(excinfo.getrepr().reprcrash.path)
         # check that importorskip reports the actual call
         # in this test the test_runner.py file
         assert path.purebasename == "test_runner"
         pytest.raises(SyntaxError, "pytest.importorskip('x y z')")
         pytest.raises(SyntaxError, "pytest.importorskip('x=y')")
-        mod = py.std.types.ModuleType("hello123")
+        mod = types.ModuleType("hello123")
         mod.__version__ = "1.3"
         monkeypatch.setitem(sys.modules, "hello123", mod)
-        pytest.raises(pytest.skip.Exception, """
+        pytest.raises(
+            pytest.skip.Exception,
+            """
             pytest.importorskip("hello123", minversion="1.3.1")
-        """)
+        """,
+        )
         mod2 = pytest.importorskip("hello123", minversion="1.3")
         assert mod2 == mod
     except pytest.skip.Exception:
         print(_pytest._code.ExceptionInfo())
         pytest.fail("spurious skip")
 
 
 def test_importorskip_imports_last_module_part():
     ospath = pytest.importorskip("os.path")
     assert os.path == ospath
 
 
 def test_importorskip_dev_module(monkeypatch):
     try:
-        mod = py.std.types.ModuleType("mockmodule")
-        mod.__version__ = '0.13.0.dev-43290'
-        monkeypatch.setitem(sys.modules, 'mockmodule', mod)
-        mod2 = pytest.importorskip('mockmodule', minversion='0.12.0')
+        mod = types.ModuleType("mockmodule")
+        mod.__version__ = "0.13.0.dev-43290"
+        monkeypatch.setitem(sys.modules, "mockmodule", mod)
+        mod2 = pytest.importorskip("mockmodule", minversion="0.12.0")
         assert mod2 == mod
-        pytest.raises(pytest.skip.Exception, """
-            pytest.importorskip('mockmodule1', minversion='0.14.0')""")
+        pytest.raises(
+            pytest.skip.Exception,
+            """
+            pytest.importorskip('mockmodule1', minversion='0.14.0')""",
+        )
     except pytest.skip.Exception:
         print(_pytest._code.ExceptionInfo())
         pytest.fail("spurious skip")
 
 
 def test_importorskip_module_level(testdir):
     """importorskip must be able to skip entire modules when used at module level"""
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         import pytest
         foobarbaz = pytest.importorskip("foobarbaz")
 
         def test_foo():
             pass
-    ''')
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines(['*collected 0 items / 1 skipped*'])
+    result.stdout.fnmatch_lines(["*collected 0 items / 1 skipped*"])
 
 
 def test_pytest_cmdline_main(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         import pytest
         def test_hello():
             assert 1
         if __name__ == '__main__':
            pytest.cmdline.main([__file__])
-    """)
+    """
+    )
     import subprocess
+
     popen = subprocess.Popen([sys.executable, str(p)], stdout=subprocess.PIPE)
     popen.communicate()
     ret = popen.wait()
     assert ret == 0
 
 
 def test_unicode_in_longrepr(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         # -*- coding: utf-8 -*-
         import pytest
         @pytest.hookimpl(hookwrapper=True)
         def pytest_runtest_makereport():
             outcome = yield
             rep = outcome.get_result()
             if rep.when == "call":
                 rep.longrepr = u'ä'
-    """)
-    testdir.makepyfile("""
+    """
+    )
+    testdir.makepyfile(
+        """
         def test_out():
             assert 0
-    """)
+    """
+    )
     result = testdir.runpytest()
     assert result.ret == 1
     assert "UnicodeEncodeError" not in result.stderr.str()
 
 
 def test_failure_in_setup(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def setup_module():
             0/0
         def test_func():
             pass
-    """)
+    """
+    )
     result = testdir.runpytest("--tb=line")
     assert "def setup_module" not in result.stdout.str()
 
 
 def test_makereport_getsource(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_foo():
             if False: pass
             else: assert False
-    """)
+    """
+    )
     result = testdir.runpytest()
-    assert 'INTERNALERROR' not in result.stdout.str()
-    result.stdout.fnmatch_lines(['*else: assert False*'])
+    assert "INTERNALERROR" not in result.stdout.str()
+    result.stdout.fnmatch_lines(["*else: assert False*"])
 
 
 def test_makereport_getsource_dynamic_code(testdir, monkeypatch):
     """Test that exception in dynamically generated code doesn't break getting the source line."""
     import inspect
+
     original_findsource = inspect.findsource
 
     def findsource(obj, *args, **kwargs):
         # Can be triggered by dynamically created functions
-        if obj.__name__ == 'foo':
+        if obj.__name__ == "foo":
             raise IndexError()
         return original_findsource(obj, *args, **kwargs)
 
-    monkeypatch.setattr(inspect, 'findsource', findsource)
+    monkeypatch.setattr(inspect, "findsource", findsource)
 
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
 
         @pytest.fixture
         def foo(missing):
             pass
 
         def test_fix(foo):
             assert False
-    """)
-    result = testdir.runpytest('-vv')
-    assert 'INTERNALERROR' not in result.stdout.str()
+    """
+    )
+    result = testdir.runpytest("-vv")
+    assert "INTERNALERROR" not in result.stdout.str()
     result.stdout.fnmatch_lines(["*test_fix*", "*fixture*'missing'*not found*"])
 
 
-def test_store_except_info_on_eror():
+def test_store_except_info_on_error():
     """ Test that upon test failure, the exception info is stored on
     sys.last_traceback and friends.
     """
-    # Simulate item that raises a specific exception
-    class ItemThatRaises(object):
-        nodeid = 'item_that_raises'
+    # Simulate item that might raise a specific exception, depending on `raise_error` class var
+    class ItemMightRaise(object):
+        nodeid = "item_that_raises"
+        raise_error = True
 
         def runtest(self):
-            raise IndexError('TEST')
+            if self.raise_error:
+                raise IndexError("TEST")
+
     try:
-        runner.pytest_runtest_call(ItemThatRaises())
+        runner.pytest_runtest_call(ItemMightRaise())
     except IndexError:
         pass
     # Check that exception info is stored on sys
     assert sys.last_type is IndexError
-    assert sys.last_value.args[0] == 'TEST'
+    assert sys.last_value.args[0] == "TEST"
     assert sys.last_traceback
 
+    # The next run should clear the exception info stored by the previous run
+    ItemMightRaise.raise_error = False
+    runner.pytest_runtest_call(ItemMightRaise())
+    assert sys.last_type is None
+    assert sys.last_value is None
+    assert sys.last_traceback is None
+
 
 def test_current_test_env_var(testdir, monkeypatch):
     pytest_current_test_vars = []
-    monkeypatch.setattr(sys, 'pytest_current_test_vars', pytest_current_test_vars, raising=False)
-    testdir.makepyfile('''
+    monkeypatch.setattr(
+        sys, "pytest_current_test_vars", pytest_current_test_vars, raising=False
+    )
+    testdir.makepyfile(
+        """
         import pytest
         import sys
         import os
 
         @pytest.fixture
         def fix():
             sys.pytest_current_test_vars.append(('setup', os.environ['PYTEST_CURRENT_TEST']))
             yield
             sys.pytest_current_test_vars.append(('teardown', os.environ['PYTEST_CURRENT_TEST']))
 
         def test(fix):
             sys.pytest_current_test_vars.append(('call', os.environ['PYTEST_CURRENT_TEST']))
-    ''')
+    """
+    )
     result = testdir.runpytest_inprocess()
     assert result.ret == 0
-    test_id = 'test_current_test_env_var.py::test'
-    assert pytest_current_test_vars == [
-        ('setup', test_id + ' (setup)'), ('call', test_id + ' (call)'), ('teardown', test_id + ' (teardown)')]
-    assert 'PYTEST_CURRENT_TEST' not in os.environ
+    test_id = "test_current_test_env_var.py::test"
+    assert (
+        pytest_current_test_vars
+        == [
+            ("setup", test_id + " (setup)"),
+            ("call", test_id + " (call)"),
+            ("teardown", test_id + " (teardown)"),
+        ]
+    )
+    assert "PYTEST_CURRENT_TEST" not in os.environ
 
 
 class TestReportContents(object):
     """
     Test user-level API of ``TestReport`` objects.
     """
 
     def getrunner(self):
         return lambda item: runner.runtestprotocol(item, log=False)
 
     def test_longreprtext_pass(self, testdir):
-        reports = testdir.runitem("""
+        reports = testdir.runitem(
+            """
             def test_func():
                 pass
-        """)
+        """
+        )
         rep = reports[1]
-        assert rep.longreprtext == ''
+        assert rep.longreprtext == ""
 
     def test_longreprtext_failure(self, testdir):
-        reports = testdir.runitem("""
+        reports = testdir.runitem(
+            """
             def test_func():
                 x = 1
                 assert x == 4
-        """)
+        """
+        )
         rep = reports[1]
-        assert 'assert 1 == 4' in rep.longreprtext
+        assert "assert 1 == 4" in rep.longreprtext
 
     def test_captured_text(self, testdir):
-        reports = testdir.runitem("""
+        reports = testdir.runitem(
+            """
             import pytest
             import sys
 
             @pytest.fixture
             def fix():
                 sys.stdout.write('setup: stdout\\n')
                 sys.stderr.write('setup: stderr\\n')
                 yield
                 sys.stdout.write('teardown: stdout\\n')
                 sys.stderr.write('teardown: stderr\\n')
                 assert 0
 
             def test_func(fix):
                 sys.stdout.write('call: stdout\\n')
                 sys.stderr.write('call: stderr\\n')
                 assert 0
-        """)
+        """
+        )
         setup, call, teardown = reports
-        assert setup.capstdout == 'setup: stdout\n'
-        assert call.capstdout == 'setup: stdout\ncall: stdout\n'
-        assert teardown.capstdout == 'setup: stdout\ncall: stdout\nteardown: stdout\n'
+        assert setup.capstdout == "setup: stdout\n"
+        assert call.capstdout == "setup: stdout\ncall: stdout\n"
+        assert teardown.capstdout == "setup: stdout\ncall: stdout\nteardown: stdout\n"
 
-        assert setup.capstderr == 'setup: stderr\n'
-        assert call.capstderr == 'setup: stderr\ncall: stderr\n'
-        assert teardown.capstderr == 'setup: stderr\ncall: stderr\nteardown: stderr\n'
+        assert setup.capstderr == "setup: stderr\n"
+        assert call.capstderr == "setup: stderr\ncall: stderr\n"
+        assert teardown.capstderr == "setup: stderr\ncall: stderr\nteardown: stderr\n"
 
     def test_no_captured_text(self, testdir):
-        reports = testdir.runitem("""
+        reports = testdir.runitem(
+            """
             def test_func():
                 pass
-        """)
+        """
+        )
         rep = reports[1]
-        assert rep.capstdout == ''
-        assert rep.capstderr == ''
+        assert rep.capstdout == ""
+        assert rep.capstderr == ""
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_runner_xunit.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_runner_xunit.py
@@ -2,17 +2,18 @@
  test correct setup/teardowns at
  module, class, and instance level
 """
 from __future__ import absolute_import, division, print_function
 import pytest
 
 
 def test_module_and_function_setup(testdir):
-    reprec = testdir.inline_runsource("""
+    reprec = testdir.inline_runsource(
+        """
         modlevel = []
         def setup_module(module):
             assert not modlevel
             module.modlevel.append(42)
 
         def teardown_module(module):
             modlevel.pop()
 
@@ -25,60 +26,66 @@ def test_module_and_function_setup(testd
         def test_modlevel():
             assert modlevel[0] == 42
             assert test_modlevel.answer == 17
 
         class TestFromClass(object):
             def test_module(self):
                 assert modlevel[0] == 42
                 assert not hasattr(test_modlevel, 'answer')
-    """)
+    """
+    )
     rep = reprec.matchreport("test_modlevel")
     assert rep.passed
     rep = reprec.matchreport("test_module")
     assert rep.passed
 
 
 def test_module_setup_failure_no_teardown(testdir):
-    reprec = testdir.inline_runsource("""
+    reprec = testdir.inline_runsource(
+        """
         values = []
         def setup_module(module):
             values.append(1)
             0/0
 
         def test_nothing():
             pass
 
         def teardown_module(module):
             values.append(2)
-    """)
+    """
+    )
     reprec.assertoutcome(failed=1)
     calls = reprec.getcalls("pytest_runtest_setup")
     assert calls[0].item.module.values == [1]
 
 
 def test_setup_function_failure_no_teardown(testdir):
-    reprec = testdir.inline_runsource("""
+    reprec = testdir.inline_runsource(
+        """
         modlevel = []
         def setup_function(function):
             modlevel.append(1)
             0/0
 
         def teardown_function(module):
             modlevel.append(2)
 
         def test_func():
             pass
-    """)
+    """
+    )
     calls = reprec.getcalls("pytest_runtest_setup")
     assert calls[0].item.module.modlevel == [1]
 
 
 def test_class_setup(testdir):
-    reprec = testdir.inline_runsource("""
+    reprec = testdir.inline_runsource(
+        """
         class TestSimpleClassSetup(object):
             clslevel = []
             def setup_class(cls):
                 cls.clslevel.append(23)
 
             def teardown_class(cls):
                 cls.clslevel.pop()
 
@@ -87,78 +94,86 @@ def test_class_setup(testdir):
 
         class TestInheritedClassSetupStillWorks(TestSimpleClassSetup):
             def test_classlevel_anothertime(self):
                 assert self.clslevel == [23]
 
         def test_cleanup():
             assert not TestSimpleClassSetup.clslevel
             assert not TestInheritedClassSetupStillWorks.clslevel
-    """)
+    """
+    )
     reprec.assertoutcome(passed=1 + 2 + 1)
 
 
 def test_class_setup_failure_no_teardown(testdir):
-    reprec = testdir.inline_runsource("""
+    reprec = testdir.inline_runsource(
+        """
         class TestSimpleClassSetup(object):
             clslevel = []
             def setup_class(cls):
                 0/0
 
             def teardown_class(cls):
                 cls.clslevel.append(1)
 
             def test_classlevel(self):
                 pass
 
         def test_cleanup():
             assert not TestSimpleClassSetup.clslevel
-    """)
+    """
+    )
     reprec.assertoutcome(failed=1, passed=1)
 
 
 def test_method_setup(testdir):
-    reprec = testdir.inline_runsource("""
+    reprec = testdir.inline_runsource(
+        """
         class TestSetupMethod(object):
             def setup_method(self, meth):
                 self.methsetup = meth
             def teardown_method(self, meth):
                 del self.methsetup
 
             def test_some(self):
                 assert self.methsetup == self.test_some
 
             def test_other(self):
                 assert self.methsetup == self.test_other
-    """)
+    """
+    )
     reprec.assertoutcome(passed=2)
 
 
 def test_method_setup_failure_no_teardown(testdir):
-    reprec = testdir.inline_runsource("""
+    reprec = testdir.inline_runsource(
+        """
         class TestMethodSetup(object):
             clslevel = []
             def setup_method(self, method):
                 self.clslevel.append(1)
                 0/0
 
             def teardown_method(self, method):
                 self.clslevel.append(2)
 
             def test_method(self):
                 pass
 
         def test_cleanup():
             assert TestMethodSetup.clslevel == [1]
-    """)
+    """
+    )
     reprec.assertoutcome(failed=1, passed=1)
 
 
 def test_method_generator_setup(testdir):
-    reprec = testdir.inline_runsource("""
+    reprec = testdir.inline_runsource(
+        """
         class TestSetupTeardownOnInstance(object):
             def setup_class(cls):
                 cls.classsetup = True
 
             def setup_method(self, method):
                 self.methsetup = method
 
             def test_generate(self):
@@ -166,22 +181,24 @@ def test_method_generator_setup(testdir)
                 assert self.methsetup == self.test_generate
                 yield self.generated, 5
                 yield self.generated, 2
 
             def generated(self, value):
                 assert self.classsetup
                 assert self.methsetup == self.test_generate
                 assert value == 5
-    """)
+    """
+    )
     reprec.assertoutcome(passed=1, failed=1)
 
 
 def test_func_generator_setup(testdir):
-    reprec = testdir.inline_runsource("""
+    reprec = testdir.inline_runsource(
+        """
         import sys
 
         def setup_module(mod):
             print ("setup_module")
             mod.x = []
 
         def setup_function(fun):
             print ("setup_function")
@@ -194,93 +211,110 @@ def test_func_generator_setup(testdir):
         def test_one():
             assert x == [1]
             def check():
                 print ("check")
                 sys.stderr.write("e\\n")
                 assert x == [1]
             yield check
             assert x == [1]
-    """)
+    """
+    )
     rep = reprec.matchreport("test_one", names="pytest_runtest_logreport")
     assert rep.passed
 
 
 def test_method_setup_uses_fresh_instances(testdir):
-    reprec = testdir.inline_runsource("""
+    reprec = testdir.inline_runsource(
+        """
         class TestSelfState1(object):
             memory = []
             def test_hello(self):
                 self.memory.append(self)
 
             def test_afterhello(self):
                 assert self != self.memory[0]
-    """)
+    """
+    )
     reprec.assertoutcome(passed=2, failed=0)
 
 
 def test_setup_that_skips_calledagain(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         import pytest
         def setup_module(mod):
             pytest.skip("x")
         def test_function1():
             pass
         def test_function2():
             pass
-    """)
+    """
+    )
     reprec = testdir.inline_run(p)
     reprec.assertoutcome(skipped=2)
 
 
 def test_setup_fails_again_on_all_tests(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         import pytest
         def setup_module(mod):
             raise ValueError(42)
         def test_function1():
             pass
         def test_function2():
             pass
-    """)
+    """
+    )
     reprec = testdir.inline_run(p)
     reprec.assertoutcome(failed=2)
 
 
 def test_setup_funcarg_setup_when_outer_scope_fails(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         import pytest
         def setup_module(mod):
             raise ValueError(42)
         @pytest.fixture
         def hello(request):
             raise ValueError("xyz43")
         def test_function1(hello):
             pass
         def test_function2(hello):
             pass
-    """)
+    """
+    )
     result = testdir.runpytest(p)
-    result.stdout.fnmatch_lines([
-        "*function1*",
-        "*ValueError*42*",
-        "*function2*",
-        "*ValueError*42*",
-        "*2 error*"
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*function1*",
+            "*ValueError*42*",
+            "*function2*",
+            "*ValueError*42*",
+            "*2 error*",
+        ]
+    )
     assert "xyz43" not in result.stdout.str()
 
 
-@pytest.mark.parametrize('arg', ['', 'arg'])
-def test_setup_teardown_function_level_with_optional_argument(testdir, monkeypatch, arg):
+@pytest.mark.parametrize("arg", ["", "arg"])
+def test_setup_teardown_function_level_with_optional_argument(
+    testdir, monkeypatch, arg
+):
     """parameter to setup/teardown xunit-style functions parameter is now optional (#1728)."""
     import sys
+
     trace_setups_teardowns = []
-    monkeypatch.setattr(sys, 'trace_setups_teardowns', trace_setups_teardowns, raising=False)
-    p = testdir.makepyfile("""
+    monkeypatch.setattr(
+        sys, "trace_setups_teardowns", trace_setups_teardowns, raising=False
+    )
+    p = testdir.makepyfile(
+        """
         import pytest
         import sys
 
         trace = sys.trace_setups_teardowns.append
 
         def setup_module({arg}): trace('setup_module')
         def teardown_module({arg}): trace('teardown_module')
 
@@ -291,29 +325,28 @@ def test_setup_teardown_function_level_w
         def test_function_2(): pass
 
         class Test(object):
             def setup_method(self, {arg}): trace('setup_method')
             def teardown_method(self, {arg}): trace('teardown_method')
 
             def test_method_1(self): pass
             def test_method_2(self): pass
-    """.format(arg=arg))
+    """.format(
+            arg=arg
+        )
+    )
     result = testdir.inline_run(p)
     result.assertoutcome(passed=4)
 
     expected = [
-        'setup_module',
-
-        'setup_function',
-        'teardown_function',
-        'setup_function',
-        'teardown_function',
-
-        'setup_method',
-        'teardown_method',
-
-        'setup_method',
-        'teardown_method',
-
-        'teardown_module',
+        "setup_module",
+        "setup_function",
+        "teardown_function",
+        "setup_function",
+        "teardown_function",
+        "setup_method",
+        "teardown_method",
+        "setup_method",
+        "teardown_method",
+        "teardown_module",
     ]
     assert trace_setups_teardowns == expected
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_session.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_session.py
@@ -1,27 +1,31 @@
 from __future__ import absolute_import, division, print_function
+
 import pytest
 
 from _pytest.main import EXIT_NOTESTSCOLLECTED
 
 
 class SessionTests(object):
+
     def test_basic_testitem_events(self, testdir):
-        tfile = testdir.makepyfile("""
+        tfile = testdir.makepyfile(
+            """
             def test_one():
                 pass
             def test_one_one():
                 assert 0
             def test_other():
                 raise ValueError(23)
             class TestClass(object):
                 def test_two(self, someargs):
                     pass
-        """)
+        """
+        )
         reprec = testdir.inline_run(tfile)
         passed, skipped, failed = reprec.listoutcomes()
         assert len(skipped) == 0
         assert len(passed) == 1
         assert len(failed) == 3
 
         def end(x):
             return x.nodeid.split("::")[-1]
@@ -31,124 +35,148 @@ class SessionTests(object):
         itemstarted = reprec.getcalls("pytest_itemcollected")
         assert len(itemstarted) == 4
         # XXX check for failing funcarg setup
         # colreports = reprec.getcalls("pytest_collectreport")
         # assert len(colreports) == 4
         # assert colreports[1].report.failed
 
     def test_nested_import_error(self, testdir):
-        tfile = testdir.makepyfile("""
+        tfile = testdir.makepyfile(
+            """
             import import_fails
             def test_this():
                 assert import_fails.a == 1
-        """, import_fails="""
+        """,
+            import_fails="""
             import does_not_work
             a = 1
-        """)
+        """,
+        )
         reprec = testdir.inline_run(tfile)
         values = reprec.getfailedcollections()
         assert len(values) == 1
         out = str(values[0].longrepr)
-        assert out.find('does_not_work') != -1
+        assert out.find("does_not_work") != -1
 
     def test_raises_output(self, testdir):
-        reprec = testdir.inline_runsource("""
+        reprec = testdir.inline_runsource(
+            """
             import pytest
             def test_raises_doesnt():
                 pytest.raises(ValueError, int, "3")
-        """)
+        """
+        )
         passed, skipped, failed = reprec.listoutcomes()
         assert len(failed) == 1
         out = failed[0].longrepr.reprcrash.message
         if not out.find("DID NOT RAISE") != -1:
             print(out)
             pytest.fail("incorrect raises() output")
 
     def test_generator_yields_None(self, testdir):
-        reprec = testdir.inline_runsource("""
+        reprec = testdir.inline_runsource(
+            """
             def test_1():
                 yield None
-        """)
+        """
+        )
         failures = reprec.getfailedcollections()
         out = failures[0].longrepr.reprcrash.message
-        i = out.find('TypeError')
+        i = out.find("TypeError")
         assert i != -1
 
     def test_syntax_error_module(self, testdir):
         reprec = testdir.inline_runsource("this is really not python")
         values = reprec.getfailedcollections()
         assert len(values) == 1
         out = str(values[0].longrepr)
-        assert out.find(str('not python')) != -1
+        assert out.find(str("not python")) != -1
 
     def test_exit_first_problem(self, testdir):
-        reprec = testdir.inline_runsource("""
+        reprec = testdir.inline_runsource(
+            """
             def test_one(): assert 0
             def test_two(): assert 0
-        """, '--exitfirst')
+        """,
+            "--exitfirst",
+        )
         passed, skipped, failed = reprec.countoutcomes()
         assert failed == 1
         assert passed == skipped == 0
 
     def test_maxfail(self, testdir):
-        reprec = testdir.inline_runsource("""
+        reprec = testdir.inline_runsource(
+            """
             def test_one(): assert 0
             def test_two(): assert 0
             def test_three(): assert 0
-        """, '--maxfail=2')
+        """,
+            "--maxfail=2",
+        )
         passed, skipped, failed = reprec.countoutcomes()
         assert failed == 2
         assert passed == skipped == 0
 
     def test_broken_repr(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             class BrokenRepr1(object):
                 foo=0
                 def __repr__(self):
                     raise Exception("Ha Ha fooled you, I'm a broken repr().")
 
             class TestBrokenClass(object):
                 def test_explicit_bad_repr(self):
                     t = BrokenRepr1()
                     pytest.raises(Exception, 'repr(t)')
 
                 def test_implicit_bad_repr1(self):
                     t = BrokenRepr1()
                     assert t.foo == 1
 
-        """)
+        """
+        )
         reprec = testdir.inline_run(p)
         passed, skipped, failed = reprec.listoutcomes()
         assert len(failed) == 1
         out = failed[0].longrepr.reprcrash.message
-        assert out.find("""[Exception("Ha Ha fooled you, I'm a broken repr().") raised in repr()]""") != -1  # '
+        assert (
+            out.find(
+                """[Exception("Ha Ha fooled you, I'm a broken repr().") raised in repr()]"""
+            )
+            != -1
+        )  # '
 
     def test_skip_file_by_conftest(self, testdir):
-        testdir.makepyfile(conftest="""
+        testdir.makepyfile(
+            conftest="""
             import pytest
             def pytest_collect_file():
                 pytest.skip("intentional")
-        """, test_file="""
+        """,
+            test_file="""
             def test_one(): pass
-        """)
+        """,
+        )
         try:
             reprec = testdir.inline_run(testdir.tmpdir)
         except pytest.skip.Exception:
             pytest.fail("wrong skipped caught")
         reports = reprec.getreports("pytest_collectreport")
         assert len(reports) == 1
         assert reports[0].skipped
 
 
 class TestNewSession(SessionTests):
 
     def test_order_of_execution(self, testdir):
-        reprec = testdir.inline_runsource("""
+        reprec = testdir.inline_runsource(
+            """
             values = []
             def test_1():
                 values.append(1)
             def test_2():
                 values.append(2)
             def test_3():
                 assert values == [1,2]
             class Testmygroup(object):
@@ -156,17 +184,18 @@ class TestNewSession(SessionTests):
                 def test_1(self):
                     self.reslist.append(1)
                 def test_2(self):
                     self.reslist.append(2)
                 def test_3(self):
                     self.reslist.append(3)
                 def test_4(self):
                     assert self.reslist == [1,2,1,2,3]
-        """)
+        """
+        )
         passed, skipped, failed = reprec.countoutcomes()
         assert failed == skipped == 0
         assert passed == 7
         # also test listnames() here ...
 
     def test_collect_only_with_various_situations(self, testdir):
         p = testdir.makepyfile(
             test_one="""
@@ -176,19 +205,19 @@ class TestNewSession(SessionTests):
                 class TestX(object):
                     def test_method_one(self):
                         pass
 
                 class TestY(TestX):
                     pass
             """,
             test_three="xxxdsadsadsadsa",
-            __init__=""
+            __init__="",
         )
-        reprec = testdir.inline_run('--collect-only', p.dirpath())
+        reprec = testdir.inline_run("--collect-only", p.dirpath())
 
         itemstarted = reprec.getcalls("pytest_itemcollected")
         assert len(itemstarted) == 3
         assert not reprec.getreports("pytest_runtest_logreport")
         started = reprec.getcalls("pytest_collectstart")
         finished = reprec.getreports("pytest_collectreport")
         assert len(started) == len(finished)
         assert len(started) == 7  # XXX extra TopCollector
@@ -208,48 +237,107 @@ class TestNewSession(SessionTests):
         testdir.makepyfile(test_one="xxxx", test_two="yyyy", test_third="zzz")
         reprec = testdir.inline_run("-x", "--maxfail=2", testdir.tmpdir)
         finished = reprec.getreports("pytest_collectreport")
         colfail = [x for x in finished if x.failed]
         assert len(colfail) == 2
 
 
 def test_plugin_specify(testdir):
-    pytest.raises(ImportError, """
+    pytest.raises(
+        ImportError,
+        """
             testdir.parseconfig("-p", "nqweotexistent")
-    """)
+    """,
+    )
     # pytest.raises(ImportError,
     #    "config.do_configure(config)"
     # )
 
 
 def test_plugin_already_exists(testdir):
     config = testdir.parseconfig("-p", "terminal")
-    assert config.option.plugins == ['terminal']
+    assert config.option.plugins == ["terminal"]
     config._do_configure()
     config._ensure_unconfigure()
 
 
 def test_exclude(testdir):
     hellodir = testdir.mkdir("hello")
     hellodir.join("test_hello.py").write("x y syntaxerror")
     hello2dir = testdir.mkdir("hello2")
     hello2dir.join("test_hello2.py").write("x y syntaxerror")
     testdir.makepyfile(test_ok="def test_pass(): pass")
     result = testdir.runpytest("--ignore=hello", "--ignore=hello2")
     assert result.ret == 0
     result.stdout.fnmatch_lines(["*1 passed*"])
 
 
+def test_deselect(testdir):
+    testdir.makepyfile(
+        test_a="""
+        import pytest
+        def test_a1(): pass
+        @pytest.mark.parametrize('b', range(3))
+        def test_a2(b): pass
+    """
+    )
+    result = testdir.runpytest(
+        "-v", "--deselect=test_a.py::test_a2[1]", "--deselect=test_a.py::test_a2[2]"
+    )
+    assert result.ret == 0
+    result.stdout.fnmatch_lines(["*2 passed, 2 deselected*"])
+    for line in result.stdout.lines:
+        assert not line.startswith(("test_a.py::test_a2[1]", "test_a.py::test_a2[2]"))
+
+
 def test_sessionfinish_with_start(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         import os
         values = []
         def pytest_sessionstart():
             values.append(os.getcwd())
             os.chdir("..")
 
         def pytest_sessionfinish():
             assert values[0] == os.getcwd()
 
-    """)
+    """
+    )
     res = testdir.runpytest("--collect-only")
     assert res.ret == EXIT_NOTESTSCOLLECTED
+
+
+@pytest.mark.parametrize("path", ["root", "{relative}/root", "{environment}/root"])
+def test_rootdir_option_arg(testdir, monkeypatch, path):
+    monkeypatch.setenv("PY_ROOTDIR_PATH", str(testdir.tmpdir))
+    path = path.format(relative=str(testdir.tmpdir), environment="$PY_ROOTDIR_PATH")
+
+    rootdir = testdir.mkdir("root")
+    rootdir.mkdir("tests")
+    testdir.makepyfile(
+        """
+        import os
+        def test_one():
+            assert 1
+    """
+    )
+
+    result = testdir.runpytest("--rootdir={}".format(path))
+    result.stdout.fnmatch_lines(
+        ["*rootdir: {}/root, inifile:*".format(testdir.tmpdir), "*1 passed*"]
+    )
+
+
+def test_rootdir_wrong_option_arg(testdir):
+    testdir.makepyfile(
+        """
+        import os
+        def test_one():
+            assert 1
+    """
+    )
+
+    result = testdir.runpytest("--rootdir=wrong_dir")
+    result.stderr.fnmatch_lines(
+        ["*Directory *wrong_dir* not found. Check your '--rootdir' option.*"]
+    )
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_skipping.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_skipping.py
@@ -2,679 +2,764 @@ from __future__ import absolute_import, 
 import pytest
 import sys
 
 from _pytest.skipping import MarkEvaluator, folded_skips, pytest_runtest_setup
 from _pytest.runner import runtestprotocol
 
 
 class TestEvaluator(object):
+
     def test_no_marker(self, testdir):
         item = testdir.getitem("def test_func(): pass")
-        evalskipif = MarkEvaluator(item, 'skipif')
+        evalskipif = MarkEvaluator(item, "skipif")
         assert not evalskipif
         assert not evalskipif.istrue()
 
     def test_marked_no_args(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             @pytest.mark.xyz
             def test_func():
                 pass
-        """)
-        ev = MarkEvaluator(item, 'xyz')
+        """
+        )
+        ev = MarkEvaluator(item, "xyz")
         assert ev
         assert ev.istrue()
         expl = ev.getexplanation()
         assert expl == ""
         assert not ev.get("run", False)
 
     def test_marked_one_arg(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             @pytest.mark.xyz("hasattr(os, 'sep')")
             def test_func():
                 pass
-        """)
-        ev = MarkEvaluator(item, 'xyz')
+        """
+        )
+        ev = MarkEvaluator(item, "xyz")
         assert ev
         assert ev.istrue()
         expl = ev.getexplanation()
         assert expl == "condition: hasattr(os, 'sep')"
 
-    @pytest.mark.skipif('sys.version_info[0] >= 3')
+    @pytest.mark.skipif("sys.version_info[0] >= 3")
     def test_marked_one_arg_unicode(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             @pytest.mark.xyz(u"hasattr(os, 'sep')")
             def test_func():
                 pass
-        """)
-        ev = MarkEvaluator(item, 'xyz')
+        """
+        )
+        ev = MarkEvaluator(item, "xyz")
         assert ev
         assert ev.istrue()
         expl = ev.getexplanation()
         assert expl == "condition: hasattr(os, 'sep')"
 
     def test_marked_one_arg_with_reason(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             @pytest.mark.xyz("hasattr(os, 'sep')", attr=2, reason="hello world")
             def test_func():
                 pass
-        """)
-        ev = MarkEvaluator(item, 'xyz')
+        """
+        )
+        ev = MarkEvaluator(item, "xyz")
         assert ev
         assert ev.istrue()
         expl = ev.getexplanation()
         assert expl == "hello world"
         assert ev.get("attr") == 2
 
     def test_marked_one_arg_twice(self, testdir):
         lines = [
-            '''@pytest.mark.skipif("not hasattr(os, 'murks')")''',
-            '''@pytest.mark.skipif("hasattr(os, 'murks')")'''
+            """@pytest.mark.skipif("not hasattr(os, 'murks')")""",
+            """@pytest.mark.skipif("hasattr(os, 'murks')")""",
         ]
         for i in range(0, 2):
-            item = testdir.getitem("""
+            item = testdir.getitem(
+                """
                 import pytest
                 %s
                 %s
                 def test_func():
                     pass
-            """ % (lines[i], lines[(i + 1) % 2]))
-            ev = MarkEvaluator(item, 'skipif')
+            """
+                % (lines[i], lines[(i + 1) % 2])
+            )
+            ev = MarkEvaluator(item, "skipif")
             assert ev
             assert ev.istrue()
             expl = ev.getexplanation()
             assert expl == "condition: not hasattr(os, 'murks')"
 
     def test_marked_one_arg_twice2(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             @pytest.mark.skipif("hasattr(os, 'murks')")
             @pytest.mark.skipif("not hasattr(os, 'murks')")
             def test_func():
                 pass
-        """)
-        ev = MarkEvaluator(item, 'skipif')
+        """
+        )
+        ev = MarkEvaluator(item, "skipif")
         assert ev
         assert ev.istrue()
         expl = ev.getexplanation()
         assert expl == "condition: not hasattr(os, 'murks')"
 
     def test_marked_skip_with_not_string(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             @pytest.mark.skipif(False)
             def test_func():
                 pass
-        """)
-        ev = MarkEvaluator(item, 'skipif')
+        """
+        )
+        ev = MarkEvaluator(item, "skipif")
         exc = pytest.raises(pytest.fail.Exception, ev.istrue)
         assert """Failed: you need to specify reason=STRING when using booleans as conditions.""" in exc.value.msg
 
     def test_skipif_class(self, testdir):
-        item, = testdir.getitems("""
+        item, = testdir.getitems(
+            """
             import pytest
             class TestClass(object):
                 pytestmark = pytest.mark.skipif("config._hackxyz")
                 def test_func(self):
                     pass
-        """)
+        """
+        )
         item.config._hackxyz = 3
-        ev = MarkEvaluator(item, 'skipif')
+        ev = MarkEvaluator(item, "skipif")
         assert ev.istrue()
         expl = ev.getexplanation()
         assert expl == "condition: config._hackxyz"
 
 
 class TestXFail(object):
 
-    @pytest.mark.parametrize('strict', [True, False])
+    @pytest.mark.parametrize("strict", [True, False])
     def test_xfail_simple(self, testdir, strict):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             @pytest.mark.xfail(strict=%s)
             def test_func():
                 assert 0
-        """ % strict)
+        """
+            % strict
+        )
         reports = runtestprotocol(item, log=False)
         assert len(reports) == 3
         callreport = reports[1]
         assert callreport.skipped
         assert callreport.wasxfail == ""
 
     def test_xfail_xpassed(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             @pytest.mark.xfail(reason="this is an xfail")
             def test_func():
                 assert 1
-        """)
+        """
+        )
         reports = runtestprotocol(item, log=False)
         assert len(reports) == 3
         callreport = reports[1]
         assert callreport.passed
         assert callreport.wasxfail == "this is an xfail"
 
+    def test_xfail_using_platform(self, testdir):
+        """
+        Verify that platform can be used with xfail statements.
+        """
+        item = testdir.getitem(
+            """
+            import pytest
+            @pytest.mark.xfail("platform.platform() == platform.platform()")
+            def test_func():
+                assert 0
+        """
+        )
+        reports = runtestprotocol(item, log=False)
+        assert len(reports) == 3
+        callreport = reports[1]
+        assert callreport.wasxfail
+
     def test_xfail_xpassed_strict(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             @pytest.mark.xfail(strict=True, reason="nope")
             def test_func():
                 assert 1
-        """)
+        """
+        )
         reports = runtestprotocol(item, log=False)
         assert len(reports) == 3
         callreport = reports[1]
         assert callreport.failed
         assert callreport.longrepr == "[XPASS(strict)] nope"
         assert not hasattr(callreport, "wasxfail")
 
     def test_xfail_run_anyway(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.xfail
             def test_func():
                 assert 0
             def test_func2():
                 pytest.xfail("hello")
-        """)
+        """
+        )
         result = testdir.runpytest("--runxfail")
-        result.stdout.fnmatch_lines([
-            "*def test_func():*",
-            "*assert 0*",
-            "*1 failed*1 pass*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*def test_func():*", "*assert 0*", "*1 failed*1 pass*"]
+        )
 
     def test_xfail_evalfalse_but_fails(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             @pytest.mark.xfail('False')
             def test_func():
                 assert 0
-        """)
+        """
+        )
         reports = runtestprotocol(item, log=False)
         callreport = reports[1]
         assert callreport.failed
         assert not hasattr(callreport, "wasxfail")
-        assert 'xfail' in callreport.keywords
+        assert "xfail" in callreport.keywords
 
     def test_xfail_not_report_default(self, testdir):
-        p = testdir.makepyfile(test_one="""
+        p = testdir.makepyfile(
+            test_one="""
             import pytest
             @pytest.mark.xfail
             def test_this():
                 assert 0
-        """)
-        testdir.runpytest(p, '-v')
+        """
+        )
+        testdir.runpytest(p, "-v")
         # result.stdout.fnmatch_lines([
         #    "*HINT*use*-r*"
         # ])
 
     def test_xfail_not_run_xfail_reporting(self, testdir):
-        p = testdir.makepyfile(test_one="""
+        p = testdir.makepyfile(
+            test_one="""
             import pytest
             @pytest.mark.xfail(run=False, reason="noway")
             def test_this():
                 assert 0
             @pytest.mark.xfail("True", run=False)
             def test_this_true():
                 assert 0
             @pytest.mark.xfail("False", run=False, reason="huh")
             def test_this_false():
                 assert 1
-        """)
-        result = testdir.runpytest(p, '-rx', )
-        result.stdout.fnmatch_lines([
-            "*test_one*test_this*",
-            "*NOTRUN*noway",
-            "*test_one*test_this_true*",
-            "*NOTRUN*condition:*True*",
-            "*1 passed*",
-        ])
+        """
+        )
+        result = testdir.runpytest(p, "-rx")
+        result.stdout.fnmatch_lines(
+            [
+                "*test_one*test_this*",
+                "*NOTRUN*noway",
+                "*test_one*test_this_true*",
+                "*NOTRUN*condition:*True*",
+                "*1 passed*",
+            ]
+        )
 
     def test_xfail_not_run_no_setup_run(self, testdir):
-        p = testdir.makepyfile(test_one="""
+        p = testdir.makepyfile(
+            test_one="""
             import pytest
             @pytest.mark.xfail(run=False, reason="hello")
             def test_this():
                 assert 0
             def setup_module(mod):
                 raise ValueError(42)
-        """)
-        result = testdir.runpytest(p, '-rx', )
-        result.stdout.fnmatch_lines([
-            "*test_one*test_this*",
-            "*NOTRUN*hello",
-            "*1 xfailed*",
-        ])
+        """
+        )
+        result = testdir.runpytest(p, "-rx")
+        result.stdout.fnmatch_lines(
+            ["*test_one*test_this*", "*NOTRUN*hello", "*1 xfailed*"]
+        )
 
     def test_xfail_xpass(self, testdir):
-        p = testdir.makepyfile(test_one="""
+        p = testdir.makepyfile(
+            test_one="""
             import pytest
             @pytest.mark.xfail
             def test_that():
                 assert 1
-        """)
-        result = testdir.runpytest(p, '-rX')
-        result.stdout.fnmatch_lines([
-            "*XPASS*test_that*",
-            "*1 xpassed*"
-        ])
+        """
+        )
+        result = testdir.runpytest(p, "-rX")
+        result.stdout.fnmatch_lines(["*XPASS*test_that*", "*1 xpassed*"])
         assert result.ret == 0
 
     def test_xfail_imperative(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             def test_this():
                 pytest.xfail("hello")
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            "*1 xfailed*",
-        ])
+        result.stdout.fnmatch_lines(["*1 xfailed*"])
         result = testdir.runpytest(p, "-rx")
-        result.stdout.fnmatch_lines([
-            "*XFAIL*test_this*",
-            "*reason:*hello*",
-        ])
+        result.stdout.fnmatch_lines(["*XFAIL*test_this*", "*reason:*hello*"])
         result = testdir.runpytest(p, "--runxfail")
         result.stdout.fnmatch_lines("*1 pass*")
 
     def test_xfail_imperative_in_setup_function(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             def setup_function(function):
                 pytest.xfail("hello")
 
             def test_this():
                 assert 0
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            "*1 xfailed*",
-        ])
+        result.stdout.fnmatch_lines(["*1 xfailed*"])
         result = testdir.runpytest(p, "-rx")
-        result.stdout.fnmatch_lines([
-            "*XFAIL*test_this*",
-            "*reason:*hello*",
-        ])
+        result.stdout.fnmatch_lines(["*XFAIL*test_this*", "*reason:*hello*"])
         result = testdir.runpytest(p, "--runxfail")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *def test_this*
             *1 fail*
-        """)
+        """
+        )
 
     def xtest_dynamic_xfail_set_during_setup(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             def setup_function(function):
                 pytest.mark.xfail(function)
             def test_this():
                 assert 0
             def test_that():
                 assert 1
-        """)
-        result = testdir.runpytest(p, '-rxX')
-        result.stdout.fnmatch_lines([
-            "*XFAIL*test_this*",
-            "*XPASS*test_that*",
-        ])
+        """
+        )
+        result = testdir.runpytest(p, "-rxX")
+        result.stdout.fnmatch_lines(["*XFAIL*test_this*", "*XPASS*test_that*"])
 
     def test_dynamic_xfail_no_run(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture
             def arg(request):
                 request.applymarker(pytest.mark.xfail(run=False))
             def test_this(arg):
                 assert 0
-        """)
-        result = testdir.runpytest(p, '-rxX')
-        result.stdout.fnmatch_lines([
-            "*XFAIL*test_this*",
-            "*NOTRUN*",
-        ])
+        """
+        )
+        result = testdir.runpytest(p, "-rxX")
+        result.stdout.fnmatch_lines(["*XFAIL*test_this*", "*NOTRUN*"])
 
     def test_dynamic_xfail_set_during_funcarg_setup(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             @pytest.fixture
             def arg(request):
                 request.applymarker(pytest.mark.xfail)
             def test_this2(arg):
                 assert 0
-        """)
+        """
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            "*1 xfailed*",
-        ])
+        result.stdout.fnmatch_lines(["*1 xfailed*"])
 
-    @pytest.mark.parametrize('expected, actual, matchline',
-                             [('TypeError', 'TypeError', "*1 xfailed*"),
-                              ('(AttributeError, TypeError)', 'TypeError', "*1 xfailed*"),
-                              ('TypeError', 'IndexError', "*1 failed*"),
-                              ('(AttributeError, TypeError)', 'IndexError', "*1 failed*"),
-                              ])
+    @pytest.mark.parametrize(
+        "expected, actual, matchline",
+        [
+            ("TypeError", "TypeError", "*1 xfailed*"),
+            ("(AttributeError, TypeError)", "TypeError", "*1 xfailed*"),
+            ("TypeError", "IndexError", "*1 failed*"),
+            ("(AttributeError, TypeError)", "IndexError", "*1 failed*"),
+        ],
+    )
     def test_xfail_raises(self, expected, actual, matchline, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.xfail(raises=%s)
             def test_raises():
                 raise %s()
-        """ % (expected, actual))
+        """
+            % (expected, actual)
+        )
         result = testdir.runpytest(p)
-        result.stdout.fnmatch_lines([
-            matchline,
-        ])
+        result.stdout.fnmatch_lines([matchline])
 
     def test_strict_sanity(self, testdir):
         """sanity check for xfail(strict=True): a failing test should behave
         exactly like a normal xfail.
         """
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.xfail(reason='unsupported feature', strict=True)
             def test_foo():
                 assert 0
-        """)
-        result = testdir.runpytest(p, '-rxX')
-        result.stdout.fnmatch_lines([
-            '*XFAIL*',
-            '*unsupported feature*',
-        ])
+        """
+        )
+        result = testdir.runpytest(p, "-rxX")
+        result.stdout.fnmatch_lines(["*XFAIL*", "*unsupported feature*"])
         assert result.ret == 0
 
-    @pytest.mark.parametrize('strict', [True, False])
+    @pytest.mark.parametrize("strict", [True, False])
     def test_strict_xfail(self, testdir, strict):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
 
             @pytest.mark.xfail(reason='unsupported feature', strict=%s)
             def test_foo():
                 with open('foo_executed', 'w'): pass  # make sure test executes
-        """ % strict)
-        result = testdir.runpytest(p, '-rxX')
+        """
+            % strict
+        )
+        result = testdir.runpytest(p, "-rxX")
         if strict:
-            result.stdout.fnmatch_lines([
-                '*test_foo*',
-                '*XPASS(strict)*unsupported feature*',
-            ])
+            result.stdout.fnmatch_lines(
+                ["*test_foo*", "*XPASS(strict)*unsupported feature*"]
+            )
         else:
-            result.stdout.fnmatch_lines([
-                '*test_strict_xfail*',
-                'XPASS test_strict_xfail.py::test_foo unsupported feature',
-            ])
+            result.stdout.fnmatch_lines(
+                [
+                    "*test_strict_xfail*",
+                    "XPASS test_strict_xfail.py::test_foo unsupported feature",
+                ]
+            )
         assert result.ret == (1 if strict else 0)
-        assert testdir.tmpdir.join('foo_executed').isfile()
+        assert testdir.tmpdir.join("foo_executed").isfile()
 
-    @pytest.mark.parametrize('strict', [True, False])
+    @pytest.mark.parametrize("strict", [True, False])
     def test_strict_xfail_condition(self, testdir, strict):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
 
             @pytest.mark.xfail(False, reason='unsupported feature', strict=%s)
             def test_foo():
                 pass
-        """ % strict)
-        result = testdir.runpytest(p, '-rxX')
-        result.stdout.fnmatch_lines('*1 passed*')
+        """
+            % strict
+        )
+        result = testdir.runpytest(p, "-rxX")
+        result.stdout.fnmatch_lines("*1 passed*")
         assert result.ret == 0
 
-    @pytest.mark.parametrize('strict', [True, False])
+    @pytest.mark.parametrize("strict", [True, False])
     def test_xfail_condition_keyword(self, testdir, strict):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
 
             @pytest.mark.xfail(condition=False, reason='unsupported feature', strict=%s)
             def test_foo():
                 pass
-        """ % strict)
-        result = testdir.runpytest(p, '-rxX')
-        result.stdout.fnmatch_lines('*1 passed*')
+        """
+            % strict
+        )
+        result = testdir.runpytest(p, "-rxX")
+        result.stdout.fnmatch_lines("*1 passed*")
         assert result.ret == 0
 
-    @pytest.mark.parametrize('strict_val', ['true', 'false'])
+    @pytest.mark.parametrize("strict_val", ["true", "false"])
     def test_strict_xfail_default_from_file(self, testdir, strict_val):
-        testdir.makeini('''
+        testdir.makeini(
+            """
             [pytest]
             xfail_strict = %s
-        ''' % strict_val)
-        p = testdir.makepyfile("""
+        """
+            % strict_val
+        )
+        p = testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.xfail(reason='unsupported feature')
             def test_foo():
                 pass
-        """)
-        result = testdir.runpytest(p, '-rxX')
-        strict = strict_val == 'true'
-        result.stdout.fnmatch_lines('*1 failed*' if strict else '*1 xpassed*')
+        """
+        )
+        result = testdir.runpytest(p, "-rxX")
+        strict = strict_val == "true"
+        result.stdout.fnmatch_lines("*1 failed*" if strict else "*1 xpassed*")
         assert result.ret == (1 if strict else 0)
 
 
 class TestXFailwithSetupTeardown(object):
+
     def test_failing_setup_issue9(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def setup_function(func):
                 assert 0
 
             @pytest.mark.xfail
             def test_func():
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*1 xfail*",
-        ])
+        result.stdout.fnmatch_lines(["*1 xfail*"])
 
     def test_failing_teardown_issue9(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def teardown_function(func):
                 assert 0
 
             @pytest.mark.xfail
             def test_func():
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*1 xfail*",
-        ])
+        result.stdout.fnmatch_lines(["*1 xfail*"])
 
 
 class TestSkip(object):
+
     def test_skip_class(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.skip
             class TestSomething(object):
                 def test_foo(self):
                     pass
                 def test_bar(self):
                     pass
 
             def test_baz():
                 pass
-        """)
+        """
+        )
         rec = testdir.inline_run()
         rec.assertoutcome(skipped=2, passed=1)
 
     def test_skips_on_false_string(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.skip('False')
             def test_foo():
                 pass
-        """)
+        """
+        )
         rec = testdir.inline_run()
         rec.assertoutcome(skipped=1)
 
     def test_arg_as_reason(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.skip('testing stuff')
             def test_bar():
                 pass
-        """)
-        result = testdir.runpytest('-rs')
-        result.stdout.fnmatch_lines([
-            "*testing stuff*",
-            "*1 skipped*",
-        ])
+        """
+        )
+        result = testdir.runpytest("-rs")
+        result.stdout.fnmatch_lines(["*testing stuff*", "*1 skipped*"])
 
     def test_skip_no_reason(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.skip
             def test_foo():
                 pass
-        """)
-        result = testdir.runpytest('-rs')
-        result.stdout.fnmatch_lines([
-            "*unconditional skip*",
-            "*1 skipped*",
-        ])
+        """
+        )
+        result = testdir.runpytest("-rs")
+        result.stdout.fnmatch_lines(["*unconditional skip*", "*1 skipped*"])
 
     def test_skip_with_reason(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.skip(reason="for lolz")
             def test_bar():
                 pass
-        """)
-        result = testdir.runpytest('-rs')
-        result.stdout.fnmatch_lines([
-            "*for lolz*",
-            "*1 skipped*",
-        ])
+        """
+        )
+        result = testdir.runpytest("-rs")
+        result.stdout.fnmatch_lines(["*for lolz*", "*1 skipped*"])
 
     def test_only_skips_marked_test(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.skip
             def test_foo():
                 pass
             @pytest.mark.skip(reason="nothing in particular")
             def test_bar():
                 pass
             def test_baz():
                 assert True
-        """)
-        result = testdir.runpytest('-rs')
-        result.stdout.fnmatch_lines([
-            "*nothing in particular*",
-            "*1 passed*2 skipped*",
-        ])
+        """
+        )
+        result = testdir.runpytest("-rs")
+        result.stdout.fnmatch_lines(["*nothing in particular*", "*1 passed*2 skipped*"])
 
     def test_strict_and_skip(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.skip
             def test_hello():
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest("-rs")
-        result.stdout.fnmatch_lines([
-            "*unconditional skip*",
-            "*1 skipped*",
-        ])
+        result.stdout.fnmatch_lines(["*unconditional skip*", "*1 skipped*"])
 
 
 class TestSkipif(object):
+
     def test_skipif_conditional(self, testdir):
-        item = testdir.getitem("""
+        item = testdir.getitem(
+            """
             import pytest
             @pytest.mark.skipif("hasattr(os, 'sep')")
             def test_func():
                 pass
-        """)  # noqa
-        x = pytest.raises(pytest.skip.Exception, lambda:
-                          pytest_runtest_setup(item))
+        """
+        )
+        x = pytest.raises(pytest.skip.Exception, lambda: pytest_runtest_setup(item))
         assert x.value.msg == "condition: hasattr(os, 'sep')"
 
-    @pytest.mark.parametrize('params', [
-        '"hasattr(sys, \'platform\')"',
-        'True, reason="invalid platform"',
-    ])
+    @pytest.mark.parametrize(
+        "params", ["\"hasattr(sys, 'platform')\"", 'True, reason="invalid platform"']
+    )
     def test_skipif_reporting(self, testdir, params):
-        p = testdir.makepyfile(test_foo="""
+        p = testdir.makepyfile(
+            test_foo="""
             import pytest
             @pytest.mark.skipif(%(params)s)
             def test_that():
                 assert 0
-        """ % dict(params=params))
-        result = testdir.runpytest(p, '-s', '-rs')
-        result.stdout.fnmatch_lines([
-            "*SKIP*1*test_foo.py*platform*",
-            "*1 skipped*"
-        ])
+        """
+            % dict(params=params)
+        )
+        result = testdir.runpytest(p, "-s", "-rs")
+        result.stdout.fnmatch_lines(["*SKIP*1*test_foo.py*platform*", "*1 skipped*"])
         assert result.ret == 0
 
-    @pytest.mark.parametrize('marker, msg1, msg2', [
-        ('skipif', 'SKIP', 'skipped'),
-        ('xfail', 'XPASS', 'xpassed'),
-    ])
+    def test_skipif_using_platform(self, testdir):
+        item = testdir.getitem(
+            """
+            import pytest
+            @pytest.mark.skipif("platform.platform() == platform.platform()")
+            def test_func():
+                pass
+        """
+        )
+        pytest.raises(pytest.skip.Exception, lambda: pytest_runtest_setup(item))
+
+    @pytest.mark.parametrize(
+        "marker, msg1, msg2",
+        [("skipif", "SKIP", "skipped"), ("xfail", "XPASS", "xpassed")],
+    )
     def test_skipif_reporting_multiple(self, testdir, marker, msg1, msg2):
-        testdir.makepyfile(test_foo="""
+        testdir.makepyfile(
+            test_foo="""
             import pytest
             @pytest.mark.{marker}(False, reason='first_condition')
             @pytest.mark.{marker}(True, reason='second_condition')
             def test_foobar():
                 assert 1
-        """.format(marker=marker))
-        result = testdir.runpytest('-s', '-rsxX')
-        result.stdout.fnmatch_lines([
-            "*{msg1}*test_foo.py*second_condition*".format(msg1=msg1),
-            "*1 {msg2}*".format(msg2=msg2),
-        ])
+        """.format(
+                marker=marker
+            )
+        )
+        result = testdir.runpytest("-s", "-rsxX")
+        result.stdout.fnmatch_lines(
+            [
+                "*{msg1}*test_foo.py*second_condition*".format(msg1=msg1),
+                "*1 {msg2}*".format(msg2=msg2),
+            ]
+        )
         assert result.ret == 0
 
 
 def test_skip_not_report_default(testdir):
-    p = testdir.makepyfile(test_one="""
+    p = testdir.makepyfile(
+        test_one="""
         import pytest
         def test_this():
             pytest.skip("hello")
-    """)
-    result = testdir.runpytest(p, '-v')
-    result.stdout.fnmatch_lines([
-        # "*HINT*use*-r*",
-        "*1 skipped*",
-    ])
+    """
+    )
+    result = testdir.runpytest(p, "-v")
+    result.stdout.fnmatch_lines(
+        [
+            # "*HINT*use*-r*",
+            "*1 skipped*"
+        ]
+    )
 
 
 def test_skipif_class(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         import pytest
 
         class TestClass(object):
             pytestmark = pytest.mark.skipif("True")
             def test_that(self):
                 assert 0
             def test_though(self):
                 assert 0
-    """)
+    """
+    )
     result = testdir.runpytest(p)
-    result.stdout.fnmatch_lines([
-        "*2 skipped*"
-    ])
+    result.stdout.fnmatch_lines(["*2 skipped*"])
 
 
 def test_skip_reasons_folding():
     path = "xyz"
     lineno = 3
     message = "justso"
     longrepr = (path, lineno, message)
 
     class X(object):
         pass
+
     ev1 = X()
     ev1.when = "execute"
     ev1.skipped = True
     ev1.longrepr = longrepr
 
     ev2 = X()
     ev2.when = "execute"
     ev2.longrepr = longrepr
@@ -705,363 +790,405 @@ def test_skipped_reasons_functional(test
             class TestClass(object):
                 def test_method(self):
                     doskip()
        """,
         conftest="""
             import pytest
             def doskip():
                 pytest.skip('test')
-        """
+        """,
     )
-    result = testdir.runpytest('-rs')
-    result.stdout.fnmatch_lines([
-        "*SKIP*2*conftest.py:4: test",
-    ])
+    result = testdir.runpytest("-rs")
+    result.stdout.fnmatch_lines(["*SKIP*2*conftest.py:4: test"])
     assert result.ret == 0
 
 
 def test_skipped_folding(testdir):
     testdir.makepyfile(
         test_one="""
             import pytest
             pytestmark = pytest.mark.skip("Folding")
             def setup_function(func):
                 pass
             def test_func():
                 pass
             class TestClass(object):
                 def test_method(self):
                     pass
-       """,
+       """
     )
-    result = testdir.runpytest('-rs')
-    result.stdout.fnmatch_lines([
-        "*SKIP*2*test_one.py: Folding"
-    ])
+    result = testdir.runpytest("-rs")
+    result.stdout.fnmatch_lines(["*SKIP*2*test_one.py: Folding"])
     assert result.ret == 0
 
 
 def test_reportchars(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         def test_1():
             assert 0
         @pytest.mark.xfail
         def test_2():
             assert 0
         @pytest.mark.xfail
         def test_3():
             pass
         def test_4():
             pytest.skip("four")
-    """)
+    """
+    )
     result = testdir.runpytest("-rfxXs")
-    result.stdout.fnmatch_lines([
-        "FAIL*test_1*",
-        "XFAIL*test_2*",
-        "XPASS*test_3*",
-        "SKIP*four*",
-    ])
+    result.stdout.fnmatch_lines(
+        ["FAIL*test_1*", "XFAIL*test_2*", "XPASS*test_3*", "SKIP*four*"]
+    )
 
 
 def test_reportchars_error(testdir):
     testdir.makepyfile(
         conftest="""
         def pytest_runtest_teardown():
             assert 0
         """,
         test_simple="""
         def test_foo():
             pass
-        """)
-    result = testdir.runpytest('-rE')
-    result.stdout.fnmatch_lines([
-        'ERROR*test_foo*',
-    ])
+        """,
+    )
+    result = testdir.runpytest("-rE")
+    result.stdout.fnmatch_lines(["ERROR*test_foo*"])
 
 
 def test_reportchars_all(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         def test_1():
             assert 0
         @pytest.mark.xfail
         def test_2():
             assert 0
         @pytest.mark.xfail
         def test_3():
             pass
         def test_4():
             pytest.skip("four")
-    """)
+    """
+    )
     result = testdir.runpytest("-ra")
-    result.stdout.fnmatch_lines([
-        "FAIL*test_1*",
-        "SKIP*four*",
-        "XFAIL*test_2*",
-        "XPASS*test_3*",
-    ])
+    result.stdout.fnmatch_lines(
+        ["FAIL*test_1*", "SKIP*four*", "XFAIL*test_2*", "XPASS*test_3*"]
+    )
 
 
 def test_reportchars_all_error(testdir):
     testdir.makepyfile(
         conftest="""
         def pytest_runtest_teardown():
             assert 0
         """,
         test_simple="""
         def test_foo():
             pass
-        """)
-    result = testdir.runpytest('-ra')
-    result.stdout.fnmatch_lines([
-        'ERROR*test_foo*',
-    ])
+        """,
+    )
+    result = testdir.runpytest("-ra")
+    result.stdout.fnmatch_lines(["ERROR*test_foo*"])
 
 
 @pytest.mark.xfail("hasattr(sys, 'pypy_version_info')")
 def test_errors_in_xfail_skip_expressions(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         @pytest.mark.skipif("asd")
         def test_nameerror():
             pass
         @pytest.mark.xfail("syntax error")
         def test_syntax():
             pass
 
         def test_func():
             pass
-    """)
+    """
+    )
     result = testdir.runpytest()
     markline = "                ^"
     if sys.platform.startswith("java"):
         # XXX report this to java
         markline = "*" + markline[8:]
-    result.stdout.fnmatch_lines([
-        "*ERROR*test_nameerror*",
-        "*evaluating*skipif*expression*",
-        "*asd*",
-        "*ERROR*test_syntax*",
-        "*evaluating*xfail*expression*",
-        "    syntax error",
-        markline,
-        "SyntaxError: invalid syntax",
-        "*1 pass*2 error*",
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*ERROR*test_nameerror*",
+            "*evaluating*skipif*expression*",
+            "*asd*",
+            "*ERROR*test_syntax*",
+            "*evaluating*xfail*expression*",
+            "    syntax error",
+            markline,
+            "SyntaxError: invalid syntax",
+            "*1 pass*2 error*",
+        ]
+    )
 
 
 def test_xfail_skipif_with_globals(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         x = 3
         @pytest.mark.skipif("x == 3")
         def test_skip1():
             pass
         @pytest.mark.xfail("x == 3")
         def test_boolean():
             assert 0
-    """)
+    """
+    )
     result = testdir.runpytest("-rsx")
-    result.stdout.fnmatch_lines([
-        "*SKIP*x == 3*",
-        "*XFAIL*test_boolean*",
-        "*x == 3*",
-    ])
+    result.stdout.fnmatch_lines(["*SKIP*x == 3*", "*XFAIL*test_boolean*", "*x == 3*"])
 
 
 def test_direct_gives_error(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         @pytest.mark.skipif(True)
         def test_skip1():
             pass
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        "*1 error*",
-    ])
+    result.stdout.fnmatch_lines(["*1 error*"])
 
 
 def test_default_markers(testdir):
     result = testdir.runpytest("--markers")
-    result.stdout.fnmatch_lines([
-        "*skipif(*condition)*skip*",
-        "*xfail(*condition, reason=None, run=True, raises=None, strict=False)*expected failure*",
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*skipif(*condition)*skip*",
+            "*xfail(*condition, reason=None, run=True, raises=None, strict=False)*expected failure*",
+        ]
+    )
 
 
 def test_xfail_test_setup_exception(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
             def pytest_runtest_setup():
                 0 / 0
-        """)
-    p = testdir.makepyfile("""
+        """
+    )
+    p = testdir.makepyfile(
+        """
             import pytest
             @pytest.mark.xfail
             def test_func():
                 assert 0
-        """)
+        """
+    )
     result = testdir.runpytest(p)
     assert result.ret == 0
-    assert 'xfailed' in result.stdout.str()
-    assert 'xpassed' not in result.stdout.str()
+    assert "xfailed" in result.stdout.str()
+    assert "xpassed" not in result.stdout.str()
 
 
 def test_imperativeskip_on_xfail_test(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         @pytest.mark.xfail
         def test_that_fails():
             assert 0
 
         @pytest.mark.skipif("True")
         def test_hello():
             pass
-    """)
-    testdir.makeconftest("""
+    """
+    )
+    testdir.makeconftest(
+        """
         import pytest
         def pytest_runtest_setup(item):
             pytest.skip("abc")
-    """)
+    """
+    )
     result = testdir.runpytest("-rsxX")
-    result.stdout.fnmatch_lines_random("""
+    result.stdout.fnmatch_lines_random(
+        """
         *SKIP*abc*
         *SKIP*condition: True*
         *2 skipped*
-    """)
+    """
+    )
 
 
 class TestBooleanCondition(object):
+
     def test_skipif(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.skipif(True, reason="True123")
             def test_func1():
                 pass
             @pytest.mark.skipif(False, reason="True123")
             def test_func2():
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *1 passed*1 skipped*
-        """)
+        """
+        )
 
     def test_skipif_noreason(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.skipif(True)
             def test_func():
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest("-rs")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *1 error*
-        """)
+        """
+        )
 
     def test_xfail(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.xfail(True, reason="True123")
             def test_func():
                 assert 0
-        """)
+        """
+        )
         result = testdir.runpytest("-rxs")
-        result.stdout.fnmatch_lines("""
+        result.stdout.fnmatch_lines(
+            """
             *XFAIL*
             *True123*
             *1 xfail*
-        """)
+        """
+        )
 
 
 def test_xfail_item(testdir):
     # Ensure pytest.xfail works with non-Python Item
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         import pytest
 
         class MyItem(pytest.Item):
             nodeid = 'foo'
             def runtest(self):
                 pytest.xfail("Expected Failure")
 
         def pytest_collect_file(path, parent):
             return MyItem("foo", parent)
-    """)
+    """
+    )
     result = testdir.inline_run()
     passed, skipped, failed = result.listoutcomes()
     assert not failed
-    xfailed = [r for r in skipped if hasattr(r, 'wasxfail')]
+    xfailed = [r for r in skipped if hasattr(r, "wasxfail")]
     assert xfailed
 
 
 def test_module_level_skip_error(testdir):
     """
     Verify that using pytest.skip at module level causes a collection error
     """
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         @pytest.skip
         def test_func():
             assert True
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines(
-        "*Using pytest.skip outside of a test is not allowed*"
-    )
+    result.stdout.fnmatch_lines("*Using pytest.skip outside of a test is not allowed*")
 
 
 def test_module_level_skip_with_allow_module_level(testdir):
     """
     Verify that using pytest.skip(allow_module_level=True) is allowed
     """
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         pytest.skip("skip_module_level", allow_module_level=True)
 
         def test_func():
             assert 0
-    """)
+    """
+    )
     result = testdir.runpytest("-rxs")
-    result.stdout.fnmatch_lines(
-        "*SKIP*skip_module_level"
-    )
+    result.stdout.fnmatch_lines("*SKIP*skip_module_level")
 
 
 def test_invalid_skip_keyword_parameter(testdir):
     """
     Verify that using pytest.skip() with unknown parameter raises an error
     """
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         pytest.skip("skip_module_level", unknown=1)
 
         def test_func():
             assert 0
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines(
-        "*TypeError:*['unknown']*"
-    )
+    result.stdout.fnmatch_lines("*TypeError:*['unknown']*")
 
 
 def test_mark_xfail_item(testdir):
     # Ensure pytest.mark.xfail works with non-Python Item
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         import pytest
 
         class MyItem(pytest.Item):
             nodeid = 'foo'
             def setup(self):
                 marker = pytest.mark.xfail(True, reason="Expected failure")
                 self.add_marker(marker)
             def runtest(self):
                 assert False
 
         def pytest_collect_file(path, parent):
             return MyItem("foo", parent)
-    """)
+    """
+    )
     result = testdir.inline_run()
     passed, skipped, failed = result.listoutcomes()
     assert not failed
-    xfailed = [r for r in skipped if hasattr(r, 'wasxfail')]
+    xfailed = [r for r in skipped if hasattr(r, "wasxfail")]
     assert xfailed
+
+
+def test_summary_list_after_errors(testdir):
+    """Ensure the list of errors/fails/xfails/skips appears after tracebacks in terminal reporting."""
+    testdir.makepyfile(
+        """
+        import pytest
+        def test_fail():
+            assert 0
+    """
+    )
+    result = testdir.runpytest("-ra")
+    result.stdout.fnmatch_lines(
+        [
+            "=* FAILURES *=",
+            "*= short test summary info =*",
+            "FAIL test_summary_list_after_errors.py::test_fail",
+        ]
+    )
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_terminal.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_terminal.py
@@ -9,664 +9,748 @@ import pluggy
 import _pytest._code
 import py
 import pytest
 from _pytest.main import EXIT_NOTESTSCOLLECTED
 from _pytest.terminal import TerminalReporter, repr_pythonversion, getreportopt
 from _pytest.terminal import build_summary_stats_line, _plugin_nameversions
 
 
-DistInfo = collections.namedtuple('DistInfo', ['project_name', 'version'])
+DistInfo = collections.namedtuple("DistInfo", ["project_name", "version"])
 
 
 class Option(object):
+
     def __init__(self, verbose=False, fulltrace=False):
         self.verbose = verbose
         self.fulltrace = fulltrace
 
     @property
     def args(self):
         values = []
         if self.verbose:
-            values.append('-v')
+            values.append("-v")
         if self.fulltrace:
-            values.append('--fulltrace')
+            values.append("--fulltrace")
         return values
 
 
-def pytest_generate_tests(metafunc):
-    if "option" in metafunc.fixturenames:
-        metafunc.addcall(id="default",
-                         funcargs={'option': Option(verbose=False)})
-        metafunc.addcall(id="verbose",
-                         funcargs={'option': Option(verbose=True)})
-        metafunc.addcall(id="quiet",
-                         funcargs={'option': Option(verbose=-1)})
-        metafunc.addcall(id="fulltrace",
-                         funcargs={'option': Option(fulltrace=True)})
+@pytest.fixture(
+    params=[
+        Option(verbose=False),
+        Option(verbose=True),
+        Option(verbose=-1),
+        Option(fulltrace=True),
+    ],
+    ids=["default", "verbose", "quiet", "fulltrace"],
+)
+def option(request):
+    return request.param
 
 
-@pytest.mark.parametrize('input,expected', [
-    ([DistInfo(project_name='test', version=1)], ['test-1']),
-    ([DistInfo(project_name='pytest-test', version=1)], ['test-1']),
-    ([
-        DistInfo(project_name='test', version=1),
-        DistInfo(project_name='test', version=1)
-    ], ['test-1']),
-], ids=['normal', 'prefix-strip', 'deduplicate'])
+@pytest.mark.parametrize(
+    "input,expected",
+    [
+        ([DistInfo(project_name="test", version=1)], ["test-1"]),
+        ([DistInfo(project_name="pytest-test", version=1)], ["test-1"]),
+        (
+            [
+                DistInfo(project_name="test", version=1),
+                DistInfo(project_name="test", version=1),
+            ],
+            ["test-1"],
+        ),
+    ],
+    ids=["normal", "prefix-strip", "deduplicate"],
+)
 def test_plugin_nameversion(input, expected):
     pluginlist = [(None, x) for x in input]
     result = _plugin_nameversions(pluginlist)
     assert result == expected
 
 
 class TestTerminal(object):
+
     def test_pass_skip_fail(self, testdir, option):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def test_ok():
                 pass
             def test_skip():
                 pytest.skip("xx")
             def test_func():
                 assert 0
-        """)
+        """
+        )
         result = testdir.runpytest(*option.args)
         if option.verbose:
-            result.stdout.fnmatch_lines([
-                "*test_pass_skip_fail.py::test_ok PASS*",
-                "*test_pass_skip_fail.py::test_skip SKIP*",
-                "*test_pass_skip_fail.py::test_func FAIL*",
-            ])
+            result.stdout.fnmatch_lines(
+                [
+                    "*test_pass_skip_fail.py::test_ok PASS*",
+                    "*test_pass_skip_fail.py::test_skip SKIP*",
+                    "*test_pass_skip_fail.py::test_func FAIL*",
+                ]
+            )
         else:
-            result.stdout.fnmatch_lines([
-                "*test_pass_skip_fail.py .sF*"
-            ])
-        result.stdout.fnmatch_lines([
-            "    def test_func():",
-            ">       assert 0",
-            "E       assert 0",
-        ])
+            result.stdout.fnmatch_lines(["*test_pass_skip_fail.py .sF*"])
+        result.stdout.fnmatch_lines(
+            ["    def test_func():", ">       assert 0", "E       assert 0"]
+        )
 
     def test_internalerror(self, testdir, linecomp):
         modcol = testdir.getmodulecol("def test_one(): pass")
         rep = TerminalReporter(modcol.config, file=linecomp.stringio)
         excinfo = pytest.raises(ValueError, "raise ValueError('hello')")
         rep.pytest_internalerror(excinfo.getrepr())
-        linecomp.assert_contains_lines([
-            "INTERNALERROR> *ValueError*hello*"
-        ])
+        linecomp.assert_contains_lines(["INTERNALERROR> *ValueError*hello*"])
 
     def test_writeline(self, testdir, linecomp):
         modcol = testdir.getmodulecol("def test_one(): pass")
         rep = TerminalReporter(modcol.config, file=linecomp.stringio)
         rep.write_fspath_result(modcol.nodeid, ".")
         rep.write_line("hello world")
-        lines = linecomp.stringio.getvalue().split('\n')
+        lines = linecomp.stringio.getvalue().split("\n")
         assert not lines[0]
         assert lines[1].endswith(modcol.name + " .")
         assert lines[2] == "hello world"
 
     def test_show_runtest_logstart(self, testdir, linecomp):
         item = testdir.getitem("def test_func(): pass")
         tr = TerminalReporter(item.config, file=linecomp.stringio)
         item.config.pluginmanager.register(tr)
         location = item.reportinfo()
-        tr.config.hook.pytest_runtest_logstart(nodeid=item.nodeid,
-                                               location=location, fspath=str(item.fspath))
-        linecomp.assert_contains_lines([
-            "*test_show_runtest_logstart.py*"
-        ])
+        tr.config.hook.pytest_runtest_logstart(
+            nodeid=item.nodeid, location=location, fspath=str(item.fspath)
+        )
+        linecomp.assert_contains_lines(["*test_show_runtest_logstart.py*"])
 
     def test_runtest_location_shown_before_test_starts(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_1():
                 import time
                 time.sleep(20)
-        """)
+        """
+        )
         child = testdir.spawn_pytest("")
         child.expect(".*test_runtest_location.*py")
         child.sendeof()
         child.kill(15)
 
     def test_itemreport_subclasses_show_subclassed_file(self, testdir):
-        testdir.makepyfile(test_p1="""
+        testdir.makepyfile(
+            test_p1="""
             class BaseTests(object):
                 def test_p1(self):
                     pass
             class TestClass(BaseTests):
                 pass
-        """)
-        p2 = testdir.makepyfile(test_p2="""
+        """
+        )
+        p2 = testdir.makepyfile(
+            test_p2="""
             from test_p1 import BaseTests
             class TestMore(BaseTests):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest(p2)
-        result.stdout.fnmatch_lines([
-            "*test_p2.py .*",
-            "*1 passed*",
-        ])
+        result.stdout.fnmatch_lines(["*test_p2.py .*", "*1 passed*"])
         result = testdir.runpytest("-v", p2)
-        result.stdout.fnmatch_lines([
-            "*test_p2.py::TestMore::test_p1* <- *test_p1.py*PASSED*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*test_p2.py::TestMore::test_p1* <- *test_p1.py*PASSED*"]
+        )
 
     def test_itemreport_directclasses_not_shown_as_subclasses(self, testdir):
         a = testdir.mkpydir("a123")
-        a.join("test_hello123.py").write(_pytest._code.Source("""
+        a.join("test_hello123.py").write(
+            _pytest._code.Source(
+                """
             class TestClass(object):
                 def test_method(self):
                     pass
-        """))
+        """
+            )
+        )
         result = testdir.runpytest("-v")
         assert result.ret == 0
-        result.stdout.fnmatch_lines([
-            "*a123/test_hello123.py*PASS*",
-        ])
+        result.stdout.fnmatch_lines(["*a123/test_hello123.py*PASS*"])
         assert " <- " not in result.stdout.str()
 
     def test_keyboard_interrupt(self, testdir, option):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_foobar():
                 assert 0
             def test_spamegg():
                 import py; pytest.skip('skip me please!')
             def test_interrupt_me():
                 raise KeyboardInterrupt   # simulating the user
-        """)
+        """
+        )
 
         result = testdir.runpytest(*option.args, no_reraise_ctrlc=True)
-        result.stdout.fnmatch_lines([
-            "    def test_foobar():",
-            ">       assert 0",
-            "E       assert 0",
-            "*_keyboard_interrupt.py:6: KeyboardInterrupt*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "    def test_foobar():",
+                ">       assert 0",
+                "E       assert 0",
+                "*_keyboard_interrupt.py:6: KeyboardInterrupt*",
+            ]
+        )
         if option.fulltrace:
-            result.stdout.fnmatch_lines([
-                "*raise KeyboardInterrupt   # simulating the user*",
-            ])
+            result.stdout.fnmatch_lines(
+                ["*raise KeyboardInterrupt   # simulating the user*"]
+            )
         else:
-            result.stdout.fnmatch_lines([
-                "to show a full traceback on KeyboardInterrupt use --fulltrace"
-            ])
-        result.stdout.fnmatch_lines(['*KeyboardInterrupt*'])
+            result.stdout.fnmatch_lines(
+                ["(to show a full traceback on KeyboardInterrupt use --fulltrace)"]
+            )
+        result.stdout.fnmatch_lines(["*KeyboardInterrupt*"])
 
     def test_keyboard_in_sessionstart(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_sessionstart():
                 raise KeyboardInterrupt
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             def test_foobar():
                 pass
-        """)
+        """
+        )
 
         result = testdir.runpytest(no_reraise_ctrlc=True)
         assert result.ret == 2
-        result.stdout.fnmatch_lines(['*KeyboardInterrupt*'])
+        result.stdout.fnmatch_lines(["*KeyboardInterrupt*"])
 
     def test_collect_single_item(self, testdir):
         """Use singular 'item' when reporting a single test item"""
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_foobar():
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines(['collected 1 item'])
+        result.stdout.fnmatch_lines(["collected 1 item"])
 
     def test_rewrite(self, testdir, monkeypatch):
         config = testdir.parseconfig()
         f = py.io.TextIO()
-        monkeypatch.setattr(f, 'isatty', lambda *args: True)
+        monkeypatch.setattr(f, "isatty", lambda *args: True)
         tr = TerminalReporter(config, f)
         tr._tw.fullwidth = 10
-        tr.write('hello')
-        tr.rewrite('hey', erase=True)
-        assert f.getvalue() == 'hello' + '\r' + 'hey' + (6 * ' ')
+        tr.write("hello")
+        tr.rewrite("hey", erase=True)
+        assert f.getvalue() == "hello" + "\r" + "hey" + (6 * " ")
 
 
 class TestCollectonly(object):
+
     def test_collectonly_basic(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_func():
                 pass
-        """)
-        result = testdir.runpytest("--collect-only",)
-        result.stdout.fnmatch_lines([
-            "<Module 'test_collectonly_basic.py'>",
-            "  <Function 'test_func'>",
-        ])
+        """
+        )
+        result = testdir.runpytest("--collect-only")
+        result.stdout.fnmatch_lines(
+            ["<Module 'test_collectonly_basic.py'>", "  <Function 'test_func'>"]
+        )
 
     def test_collectonly_skipped_module(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             pytest.skip("hello")
-        """)
+        """
+        )
         result = testdir.runpytest("--collect-only", "-rs")
-        result.stdout.fnmatch_lines([
-            "*ERROR collecting*",
-        ])
+        result.stdout.fnmatch_lines(["*ERROR collecting*"])
 
     def test_collectonly_failed_module(self, testdir):
         testdir.makepyfile("""raise ValueError(0)""")
         result = testdir.runpytest("--collect-only")
-        result.stdout.fnmatch_lines([
-            "*raise ValueError*",
-            "*1 error*",
-        ])
+        result.stdout.fnmatch_lines(["*raise ValueError*", "*1 error*"])
 
     def test_collectonly_fatal(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_collectstart(collector):
                 assert 0, "urgs"
-        """)
+        """
+        )
         result = testdir.runpytest("--collect-only")
-        result.stdout.fnmatch_lines([
-            "*INTERNAL*args*"
-        ])
+        result.stdout.fnmatch_lines(["*INTERNAL*args*"])
         assert result.ret == 3
 
     def test_collectonly_simple(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_func1():
                 pass
             class TestClass(object):
                 def test_method(self):
                     pass
-        """)
+        """
+        )
         result = testdir.runpytest("--collect-only", p)
         # assert stderr.startswith("inserting into sys.path")
         assert result.ret == 0
-        result.stdout.fnmatch_lines([
-            "*<Module '*.py'>",
-            "* <Function 'test_func1'*>",
-            "* <Class 'TestClass'>",
-            # "*  <Instance '()'>",
-            "*   <Function 'test_method'*>",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*<Module '*.py'>",
+                "* <Function 'test_func1'*>",
+                "* <Class 'TestClass'>",
+                # "*  <Instance '()'>",
+                "*   <Function 'test_method'*>",
+            ]
+        )
 
     def test_collectonly_error(self, testdir):
         p = testdir.makepyfile("import Errlkjqweqwe")
         result = testdir.runpytest("--collect-only", p)
         assert result.ret == 2
-        result.stdout.fnmatch_lines(_pytest._code.Source("""
+        result.stdout.fnmatch_lines(
+            _pytest._code.Source(
+                """
             *ERROR*
             *ImportError*
             *No module named *Errlk*
             *1 error*
-        """).strip())
+        """
+            ).strip()
+        )
 
     def test_collectonly_missing_path(self, testdir):
         """this checks issue 115,
             failure in parseargs will cause session
             not to have the items attribute
         """
         result = testdir.runpytest("--collect-only", "uhm_missing_path")
         assert result.ret == 4
-        result.stderr.fnmatch_lines([
-            '*ERROR: file not found*',
-        ])
+        result.stderr.fnmatch_lines(["*ERROR: file not found*"])
 
     def test_collectonly_quiet(self, testdir):
         testdir.makepyfile("def test_foo(): pass")
         result = testdir.runpytest("--collect-only", "-q")
-        result.stdout.fnmatch_lines([
-            '*test_foo*',
-        ])
+        result.stdout.fnmatch_lines(["*test_foo*"])
 
     def test_collectonly_more_quiet(self, testdir):
         testdir.makepyfile(test_fun="def test_foo(): pass")
         result = testdir.runpytest("--collect-only", "-qq")
-        result.stdout.fnmatch_lines([
-            '*test_fun.py: 1*',
-        ])
+        result.stdout.fnmatch_lines(["*test_fun.py: 1*"])
 
 
 def test_repr_python_version(monkeypatch):
     try:
-        monkeypatch.setattr(sys, 'version_info', (2, 5, 1, 'final', 0))
+        monkeypatch.setattr(sys, "version_info", (2, 5, 1, "final", 0))
         assert repr_pythonversion() == "2.5.1-final-0"
-        py.std.sys.version_info = x = (2, 3)
+        sys.version_info = x = (2, 3)
         assert repr_pythonversion() == str(x)
     finally:
         monkeypatch.undo()  # do this early as pytest can get confused
 
 
 class TestFixtureReporting(object):
+
     def test_setup_fixture_error(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def setup_function(function):
                 print ("setup func")
                 assert 0
             def test_nada():
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*ERROR at setup of test_nada*",
-            "*setup_function(function):*",
-            "*setup func*",
-            "*assert 0*",
-            "*1 error*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*ERROR at setup of test_nada*",
+                "*setup_function(function):*",
+                "*setup func*",
+                "*assert 0*",
+                "*1 error*",
+            ]
+        )
         assert result.ret != 0
 
     def test_teardown_fixture_error(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_nada():
                 pass
             def teardown_function(function):
                 print ("teardown func")
                 assert 0
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*ERROR at teardown*",
-            "*teardown_function(function):*",
-            "*assert 0*",
-            "*Captured stdout*",
-            "*teardown func*",
-            "*1 passed*1 error*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*ERROR at teardown*",
+                "*teardown_function(function):*",
+                "*assert 0*",
+                "*Captured stdout*",
+                "*teardown func*",
+                "*1 passed*1 error*",
+            ]
+        )
 
     def test_teardown_fixture_error_and_test_failure(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_fail():
                 assert 0, "failingfunc"
 
             def teardown_function(function):
                 print ("teardown func")
                 assert False
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*ERROR at teardown of test_fail*",
-            "*teardown_function(function):*",
-            "*assert False*",
-            "*Captured stdout*",
-            "*teardown func*",
-
-            "*test_fail*",
-            "*def test_fail():",
-            "*failingfunc*",
-            "*1 failed*1 error*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*ERROR at teardown of test_fail*",
+                "*teardown_function(function):*",
+                "*assert False*",
+                "*Captured stdout*",
+                "*teardown func*",
+                "*test_fail*",
+                "*def test_fail():",
+                "*failingfunc*",
+                "*1 failed*1 error*",
+            ]
+        )
 
     def test_setup_teardown_output_and_test_failure(self, testdir):
         """ Test for issue #442 """
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def setup_function(function):
                 print ("setup func")
 
             def test_fail():
                 assert 0, "failingfunc"
 
             def teardown_function(function):
                 print ("teardown func")
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*test_fail*",
-            "*def test_fail():",
-            "*failingfunc*",
-            "*Captured stdout setup*",
-            "*setup func*",
-            "*Captured stdout teardown*",
-            "*teardown func*",
-
-            "*1 failed*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*test_fail*",
+                "*def test_fail():",
+                "*failingfunc*",
+                "*Captured stdout setup*",
+                "*setup func*",
+                "*Captured stdout teardown*",
+                "*teardown func*",
+                "*1 failed*",
+            ]
+        )
 
 
 class TestTerminalFunctional(object):
+
     def test_deselected(self, testdir):
-        testpath = testdir.makepyfile("""
+        testpath = testdir.makepyfile(
+            """
                 def test_one():
                     pass
                 def test_two():
                     pass
                 def test_three():
                     pass
            """
-                                      )
+        )
         result = testdir.runpytest("-k", "test_two:", testpath)
-        result.stdout.fnmatch_lines([
-            "*test_deselected.py ..*",
-            "=* 1 test*deselected *=",
-        ])
+        result.stdout.fnmatch_lines(
+            ["collected 3 items / 1 deselected", "*test_deselected.py ..*"]
+        )
+        assert result.ret == 0
+
+    def test_show_deselected_items_using_markexpr_before_test_execution(self, testdir):
+        testdir.makepyfile(
+            """
+            import pytest
+
+            @pytest.mark.foo
+            def test_foobar():
+                pass
+
+            @pytest.mark.bar
+            def test_bar():
+                pass
+
+            def test_pass():
+                pass
+        """
+        )
+        result = testdir.runpytest("-m", "not foo")
+        result.stdout.fnmatch_lines(
+            [
+                "collected 3 items / 1 deselected",
+                "*test_show_des*.py ..*",
+                "*= 2 passed, 1 deselected in * =*",
+            ]
+        )
+        assert "= 1 deselected =" not in result.stdout.str()
         assert result.ret == 0
 
     def test_no_skip_summary_if_failure(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def test_ok():
                 pass
             def test_fail():
                 assert 0
             def test_skip():
                 pytest.skip("dontshow")
-        """)
+        """
+        )
         result = testdir.runpytest()
         assert result.stdout.str().find("skip test summary") == -1
         assert result.ret == 1
 
     def test_passes(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             def test_passes():
                 pass
             class TestClass(object):
                 def test_method(self):
                     pass
-        """)
+        """
+        )
         old = p1.dirpath().chdir()
         try:
             result = testdir.runpytest()
         finally:
             old.chdir()
-        result.stdout.fnmatch_lines([
-            "test_passes.py ..*",
-            "* 2 pass*",
-        ])
+        result.stdout.fnmatch_lines(["test_passes.py ..*", "* 2 pass*"])
         assert result.ret == 0
 
     def test_header_trailer_info(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_passes():
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        verinfo = ".".join(map(str, py.std.sys.version_info[:3]))
-        result.stdout.fnmatch_lines([
-            "*===== test session starts ====*",
-            "platform %s -- Python %s*pytest-%s*py-%s*pluggy-%s" % (
-                py.std.sys.platform, verinfo,
-                pytest.__version__, py.__version__, pluggy.__version__),
-            "*test_header_trailer_info.py .*",
-            "=* 1 passed*in *.[0-9][0-9] seconds *=",
-        ])
+        verinfo = ".".join(map(str, sys.version_info[:3]))
+        result.stdout.fnmatch_lines(
+            [
+                "*===== test session starts ====*",
+                "platform %s -- Python %s*pytest-%s*py-%s*pluggy-%s"
+                % (
+                    sys.platform,
+                    verinfo,
+                    pytest.__version__,
+                    py.__version__,
+                    pluggy.__version__,
+                ),
+                "*test_header_trailer_info.py .*",
+                "=* 1 passed*in *.[0-9][0-9] seconds *=",
+            ]
+        )
         if pytest.config.pluginmanager.list_plugin_distinfo():
-            result.stdout.fnmatch_lines([
-                "plugins: *",
-            ])
+            result.stdout.fnmatch_lines(["plugins: *"])
 
     def test_showlocals(self, testdir):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             def test_showlocals():
                 x = 3
                 y = "x" * 5000
                 assert 0
-        """)
-        result = testdir.runpytest(p1, '-l')
-        result.stdout.fnmatch_lines([
-            # "_ _ * Locals *",
-            "x* = 3",
-            "y* = 'xxxxxx*"
-        ])
+        """
+        )
+        result = testdir.runpytest(p1, "-l")
+        result.stdout.fnmatch_lines(
+            [
+                # "_ _ * Locals *",
+                "x* = 3",
+                "y* = 'xxxxxx*",
+            ]
+        )
 
     def test_verbose_reporting(self, testdir, pytestconfig):
-        p1 = testdir.makepyfile("""
+        p1 = testdir.makepyfile(
+            """
             import pytest
             def test_fail():
                 raise ValueError()
             def test_pass():
                 pass
             class TestClass(object):
                 def test_skip(self):
                     pytest.skip("hello")
             def test_gen():
                 def check(x):
                     assert x == 1
                 yield check, 0
-        """)
-        result = testdir.runpytest(p1, '-v')
-        result.stdout.fnmatch_lines([
-            "*test_verbose_reporting.py::test_fail *FAIL*",
-            "*test_verbose_reporting.py::test_pass *PASS*",
-            "*test_verbose_reporting.py::TestClass::test_skip *SKIP*",
-            "*test_verbose_reporting.py::test_gen*0* *FAIL*",
-        ])
+        """
+        )
+        result = testdir.runpytest(p1, "-v")
+        result.stdout.fnmatch_lines(
+            [
+                "*test_verbose_reporting.py::test_fail *FAIL*",
+                "*test_verbose_reporting.py::test_pass *PASS*",
+                "*test_verbose_reporting.py::TestClass::test_skip *SKIP*",
+                "*test_verbose_reporting.py::test_gen*0* *FAIL*",
+            ]
+        )
         assert result.ret == 1
 
         if not pytestconfig.pluginmanager.get_plugin("xdist"):
             pytest.skip("xdist plugin not installed")
 
-        result = testdir.runpytest(p1, '-v', '-n 1')
-        result.stdout.fnmatch_lines([
-            "*FAIL*test_verbose_reporting.py::test_fail*",
-        ])
+        result = testdir.runpytest(p1, "-v", "-n 1")
+        result.stdout.fnmatch_lines(["*FAIL*test_verbose_reporting.py::test_fail*"])
         assert result.ret == 1
 
     def test_quiet_reporting(self, testdir):
         p1 = testdir.makepyfile("def test_pass(): pass")
-        result = testdir.runpytest(p1, '-q')
+        result = testdir.runpytest(p1, "-q")
         s = result.stdout.str()
-        assert 'test session starts' not in s
+        assert "test session starts" not in s
         assert p1.basename not in s
         assert "===" not in s
         assert "passed" in s
 
     def test_more_quiet_reporting(self, testdir):
         p1 = testdir.makepyfile("def test_pass(): pass")
-        result = testdir.runpytest(p1, '-qq')
+        result = testdir.runpytest(p1, "-qq")
         s = result.stdout.str()
-        assert 'test session starts' not in s
+        assert "test session starts" not in s
         assert p1.basename not in s
         assert "===" not in s
         assert "passed" not in s
 
     def test_report_collectionfinish_hook(self, testdir):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_report_collectionfinish(config, startdir, items):
                 return ['hello from hook: {0} items'.format(len(items))]
-        """)
-        testdir.makepyfile("""
+        """
+        )
+        testdir.makepyfile(
+            """
             import pytest
             @pytest.mark.parametrize('i', range(3))
             def test(i):
                 pass
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "collected 3 items",
-            "hello from hook: 3 items",
-        ])
+        result.stdout.fnmatch_lines(["collected 3 items", "hello from hook: 3 items"])
 
 
 def test_fail_extra_reporting(testdir):
     testdir.makepyfile("def test_this(): assert 0")
     result = testdir.runpytest()
-    assert 'short test summary' not in result.stdout.str()
-    result = testdir.runpytest('-rf')
-    result.stdout.fnmatch_lines([
-        "*test summary*",
-        "FAIL*test_fail_extra_reporting*",
-    ])
+    assert "short test summary" not in result.stdout.str()
+    result = testdir.runpytest("-rf")
+    result.stdout.fnmatch_lines(["*test summary*", "FAIL*test_fail_extra_reporting*"])
 
 
 def test_fail_reporting_on_pass(testdir):
     testdir.makepyfile("def test_this(): assert 1")
-    result = testdir.runpytest('-rf')
-    assert 'short test summary' not in result.stdout.str()
+    result = testdir.runpytest("-rf")
+    assert "short test summary" not in result.stdout.str()
 
 
 def test_pass_extra_reporting(testdir):
     testdir.makepyfile("def test_this(): assert 1")
     result = testdir.runpytest()
-    assert 'short test summary' not in result.stdout.str()
-    result = testdir.runpytest('-rp')
-    result.stdout.fnmatch_lines([
-        "*test summary*",
-        "PASS*test_pass_extra_reporting*",
-    ])
+    assert "short test summary" not in result.stdout.str()
+    result = testdir.runpytest("-rp")
+    result.stdout.fnmatch_lines(["*test summary*", "PASS*test_pass_extra_reporting*"])
 
 
 def test_pass_reporting_on_fail(testdir):
     testdir.makepyfile("def test_this(): assert 0")
-    result = testdir.runpytest('-rp')
-    assert 'short test summary' not in result.stdout.str()
+    result = testdir.runpytest("-rp")
+    assert "short test summary" not in result.stdout.str()
 
 
 def test_pass_output_reporting(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         def test_pass_output():
             print("Four score and seven years ago...")
-    """)
+    """
+    )
     result = testdir.runpytest()
-    assert 'Four score and seven years ago...' not in result.stdout.str()
-    result = testdir.runpytest('-rP')
-    result.stdout.fnmatch_lines([
-        "Four score and seven years ago...",
-    ])
+    assert "Four score and seven years ago..." not in result.stdout.str()
+    result = testdir.runpytest("-rP")
+    result.stdout.fnmatch_lines(["Four score and seven years ago..."])
 
 
 def test_color_yes(testdir):
     testdir.makepyfile("def test_this(): assert 1")
-    result = testdir.runpytest('--color=yes')
-    assert 'test session starts' in result.stdout.str()
-    assert '\x1b[1m' in result.stdout.str()
+    result = testdir.runpytest("--color=yes")
+    assert "test session starts" in result.stdout.str()
+    assert "\x1b[1m" in result.stdout.str()
 
 
 def test_color_no(testdir):
     testdir.makepyfile("def test_this(): assert 1")
-    result = testdir.runpytest('--color=no')
-    assert 'test session starts' in result.stdout.str()
-    assert '\x1b[1m' not in result.stdout.str()
+    result = testdir.runpytest("--color=no")
+    assert "test session starts" in result.stdout.str()
+    assert "\x1b[1m" not in result.stdout.str()
 
 
-@pytest.mark.parametrize('verbose', [True, False])
+@pytest.mark.parametrize("verbose", [True, False])
 def test_color_yes_collection_on_non_atty(testdir, verbose):
     """skip collect progress report when working on non-terminals.
     #1397
     """
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         @pytest.mark.parametrize('i', range(10))
         def test_this(i):
             assert 1
-    """)
-    args = ['--color=yes']
+    """
+    )
+    args = ["--color=yes"]
     if verbose:
-        args.append('-vv')
+        args.append("-vv")
     result = testdir.runpytest(*args)
-    assert 'test session starts' in result.stdout.str()
-    assert '\x1b[1m' in result.stdout.str()
-    assert 'collecting 10 items' not in result.stdout.str()
+    assert "test session starts" in result.stdout.str()
+    assert "\x1b[1m" in result.stdout.str()
+    assert "collecting 10 items" not in result.stdout.str()
     if verbose:
-        assert 'collecting ...' in result.stdout.str()
-    assert 'collected 10 items' in result.stdout.str()
+        assert "collecting ..." in result.stdout.str()
+    assert "collected 10 items" in result.stdout.str()
 
 
 def test_getreportopt():
-    class config(object):
-        class option(object):
+
+    class Config(object):
+
+        class Option(object):
             reportchars = ""
             disable_warnings = True
 
+        option = Option()
+
+    config = Config()
+
     config.option.reportchars = "sf"
     assert getreportopt(config) == "sf"
 
     config.option.reportchars = "sfxw"
     assert getreportopt(config) == "sfx"
 
     config.option.reportchars = "sfx"
     config.option.disable_warnings = False
@@ -674,307 +758,358 @@ def test_getreportopt():
 
     config.option.reportchars = "sfxw"
     config.option.disable_warnings = False
     assert getreportopt(config) == "sfxw"
 
 
 def test_terminalreporter_reportopt_addopts(testdir):
     testdir.makeini("[pytest]\naddopts=-rs")
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
 
         @pytest.fixture
         def tr(request):
             tr = request.config.pluginmanager.getplugin("terminalreporter")
             return tr
         def test_opt(tr):
             assert tr.hasopt('skipped')
             assert not tr.hasopt('qwe')
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        "*1 passed*"
-    ])
+    result.stdout.fnmatch_lines(["*1 passed*"])
 
 
 def test_tbstyle_short(testdir):
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         import pytest
 
         @pytest.fixture
         def arg(request):
             return 42
         def test_opt(arg):
             x = 0
             assert x
-    """)
+    """
+    )
     result = testdir.runpytest("--tb=short")
     s = result.stdout.str()
-    assert 'arg = 42' not in s
-    assert 'x = 0' not in s
-    result.stdout.fnmatch_lines([
-        "*%s:8*" % p.basename,
-        "    assert x",
-        "E   assert*",
-    ])
+    assert "arg = 42" not in s
+    assert "x = 0" not in s
+    result.stdout.fnmatch_lines(["*%s:8*" % p.basename, "    assert x", "E   assert*"])
     result = testdir.runpytest()
     s = result.stdout.str()
-    assert 'x = 0' in s
-    assert 'assert x' in s
+    assert "x = 0" in s
+    assert "assert x" in s
 
 
 def test_traceconfig(testdir, monkeypatch):
     result = testdir.runpytest("--traceconfig")
-    result.stdout.fnmatch_lines([
-        "*active plugins*"
-    ])
+    result.stdout.fnmatch_lines(["*active plugins*"])
     assert result.ret == EXIT_NOTESTSCOLLECTED
 
 
 class TestGenericReporting(object):
     """ this test class can be subclassed with a different option
         provider to run e.g. distributed tests.
     """
 
     def test_collect_fail(self, testdir, option):
         testdir.makepyfile("import xyz\n")
         result = testdir.runpytest(*option.args)
-        result.stdout.fnmatch_lines([
-            "ImportError while importing*",
-            "*No module named *xyz*",
-            "*1 error*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["ImportError while importing*", "*No module named *xyz*", "*1 error*"]
+        )
 
     def test_maxfailures(self, testdir, option):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             def test_1():
                 assert 0
             def test_2():
                 assert 0
             def test_3():
                 assert 0
-        """)
+        """
+        )
         result = testdir.runpytest("--maxfail=2", *option.args)
-        result.stdout.fnmatch_lines([
-            "*def test_1():*",
-            "*def test_2():*",
-            "*2 failed*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*def test_1():*", "*def test_2():*", "*2 failed*"]
+        )
 
     def test_tb_option(self, testdir, option):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             import pytest
             def g():
                 raise IndexError
             def test_func():
                 print (6*7)
                 g()  # --calling--
-        """)
+        """
+        )
         for tbopt in ["long", "short", "no"]:
-            print('testing --tb=%s...' % tbopt)
-            result = testdir.runpytest('--tb=%s' % tbopt)
+            print("testing --tb=%s..." % tbopt)
+            result = testdir.runpytest("--tb=%s" % tbopt)
             s = result.stdout.str()
             if tbopt == "long":
-                assert 'print (6*7)' in s
+                assert "print (6*7)" in s
             else:
-                assert 'print (6*7)' not in s
+                assert "print (6*7)" not in s
             if tbopt != "no":
-                assert '--calling--' in s
-                assert 'IndexError' in s
+                assert "--calling--" in s
+                assert "IndexError" in s
             else:
-                assert 'FAILURES' not in s
-                assert '--calling--' not in s
-                assert 'IndexError' not in s
+                assert "FAILURES" not in s
+                assert "--calling--" not in s
+                assert "IndexError" not in s
 
     def test_tb_crashline(self, testdir, option):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             import pytest
             def g():
                 raise IndexError
             def test_func1():
                 print (6*7)
                 g()  # --calling--
             def test_func2():
                 assert 0, "hello"
-        """)
+        """
+        )
         result = testdir.runpytest("--tb=line")
         bn = p.basename
-        result.stdout.fnmatch_lines([
-            "*%s:3: IndexError*" % bn,
-            "*%s:8: AssertionError: hello*" % bn,
-        ])
+        result.stdout.fnmatch_lines(
+            ["*%s:3: IndexError*" % bn, "*%s:8: AssertionError: hello*" % bn]
+        )
         s = result.stdout.str()
         assert "def test_func2" not in s
 
     def test_pytest_report_header(self, testdir, option):
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
             def pytest_sessionstart(session):
                 session.config._somevalue = 42
             def pytest_report_header(config):
                 return "hello: %s" % config._somevalue
-        """)
-        testdir.mkdir("a").join("conftest.py").write("""
+        """
+        )
+        testdir.mkdir("a").join("conftest.py").write(
+            """
 def pytest_report_header(config, startdir):
     return ["line1", str(startdir)]
-""")
+"""
+        )
         result = testdir.runpytest("a")
-        result.stdout.fnmatch_lines([
-            "*hello: 42*",
-            "line1",
-            str(testdir.tmpdir),
-        ])
+        result.stdout.fnmatch_lines(["*hello: 42*", "line1", str(testdir.tmpdir)])
+
+    def test_show_capture(self, testdir):
+        testdir.makepyfile(
+            """
+            import sys
+            import logging
+            def test_one():
+                sys.stdout.write('!This is stdout!')
+                sys.stderr.write('!This is stderr!')
+                logging.warning('!This is a warning log msg!')
+                assert False, 'Something failed'
+        """
+        )
+
+        result = testdir.runpytest("--tb=short")
+        result.stdout.fnmatch_lines(
+            [
+                "!This is stdout!",
+                "!This is stderr!",
+                "*WARNING*!This is a warning log msg!",
+            ]
+        )
+
+        result = testdir.runpytest("--show-capture=all", "--tb=short")
+        result.stdout.fnmatch_lines(
+            [
+                "!This is stdout!",
+                "!This is stderr!",
+                "*WARNING*!This is a warning log msg!",
+            ]
+        )
+
+        stdout = testdir.runpytest("--show-capture=stdout", "--tb=short").stdout.str()
+        assert "!This is stderr!" not in stdout
+        assert "!This is stdout!" in stdout
+        assert "!This is a warning log msg!" not in stdout
+
+        stdout = testdir.runpytest("--show-capture=stderr", "--tb=short").stdout.str()
+        assert "!This is stdout!" not in stdout
+        assert "!This is stderr!" in stdout
+        assert "!This is a warning log msg!" not in stdout
+
+        stdout = testdir.runpytest("--show-capture=log", "--tb=short").stdout.str()
+        assert "!This is stdout!" not in stdout
+        assert "!This is stderr!" not in stdout
+        assert "!This is a warning log msg!" in stdout
+
+        stdout = testdir.runpytest("--show-capture=no", "--tb=short").stdout.str()
+        assert "!This is stdout!" not in stdout
+        assert "!This is stderr!" not in stdout
+        assert "!This is a warning log msg!" not in stdout
 
 
 @pytest.mark.xfail("not hasattr(os, 'dup')")
 def test_fdopen_kept_alive_issue124(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import os, sys
         k = []
         def test_open_file_and_keep_alive(capfd):
             stdout = os.fdopen(1, 'w', 1)
             k.append(stdout)
 
         def test_close_kept_alive_file():
             stdout = k.pop()
             stdout.close()
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        "*2 passed*"
-    ])
+    result.stdout.fnmatch_lines(["*2 passed*"])
 
 
 def test_tbstyle_native_setup_error(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         @pytest.fixture
         def setup_error_fixture():
             raise Exception("error in exception")
 
         def test_error_fixture(setup_error_fixture):
             pass
-    """)
+    """
+    )
     result = testdir.runpytest("--tb=native")
-    result.stdout.fnmatch_lines([
-        '*File *test_tbstyle_native_setup_error.py", line *, in setup_error_fixture*'
-    ])
+    result.stdout.fnmatch_lines(
+        ['*File *test_tbstyle_native_setup_error.py", line *, in setup_error_fixture*']
+    )
 
 
 def test_terminal_summary(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         def pytest_terminal_summary(terminalreporter, exitstatus):
             w = terminalreporter
             w.section("hello")
             w.line("world")
             w.line("exitstatus: {0}".format(exitstatus))
-    """)
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines("""
+    result.stdout.fnmatch_lines(
+        """
         *==== hello ====*
         world
         exitstatus: 5
-    """)
+    """
+    )
 
 
 def test_terminal_summary_warnings_are_displayed(testdir):
     """Test that warnings emitted during pytest_terminal_summary are displayed.
     (#1305).
     """
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         def pytest_terminal_summary(terminalreporter):
             config = terminalreporter.config
             config.warn('C1', 'internal warning')
-    """)
-    result = testdir.runpytest('-rw')
-    result.stdout.fnmatch_lines([
-        '*internal warning',
-        '*== 1 warnings in *',
-    ])
-
-
-@pytest.mark.parametrize("exp_color, exp_line, stats_arg", [
-    # The method under test only cares about the length of each
-    # dict value, not the actual contents, so tuples of anything
-    # suffice
-
-    # Important statuses -- the highest priority of these always wins
-    ("red", "1 failed", {"failed": (1,)}),
-    ("red", "1 failed, 1 passed", {"failed": (1,), "passed": (1,)}),
-
-    ("red", "1 error", {"error": (1,)}),
-    ("red", "1 passed, 1 error", {"error": (1,), "passed": (1,)}),
-
-    # (a status that's not known to the code)
-    ("yellow", "1 weird", {"weird": (1,)}),
-    ("yellow", "1 passed, 1 weird", {"weird": (1,), "passed": (1,)}),
-
-    ("yellow", "1 warnings", {"warnings": (1,)}),
-    ("yellow", "1 passed, 1 warnings", {"warnings": (1,),
-                                        "passed": (1,)}),
-
-    ("green", "5 passed", {"passed": (1, 2, 3, 4, 5)}),
+    """
+    )
+    result = testdir.runpytest("-rw")
+    result.stdout.fnmatch_lines(
+        ["<undetermined location>", "*internal warning", "*== 1 warnings in *"]
+    )
+    assert "None" not in result.stdout.str()
 
 
-    # "Boring" statuses.  These have no effect on the color of the summary
-    # line.  Thus, if *every* test has a boring status, the summary line stays
-    # at its default color, i.e. yellow, to warn the user that the test run
-    # produced no useful information
-    ("yellow", "1 skipped", {"skipped": (1,)}),
-    ("green", "1 passed, 1 skipped", {"skipped": (1,), "passed": (1,)}),
-
-    ("yellow", "1 deselected", {"deselected": (1,)}),
-    ("green", "1 passed, 1 deselected", {"deselected": (1,), "passed": (1,)}),
-
-    ("yellow", "1 xfailed", {"xfailed": (1,)}),
-    ("green", "1 passed, 1 xfailed", {"xfailed": (1,), "passed": (1,)}),
-
-    ("yellow", "1 xpassed", {"xpassed": (1,)}),
-    ("green", "1 passed, 1 xpassed", {"xpassed": (1,), "passed": (1,)}),
-
-    # Likewise if no tests were found at all
-    ("yellow", "no tests ran", {}),
-
-    # Test the empty-key special case
-    ("yellow", "no tests ran", {"": (1,)}),
-    ("green", "1 passed", {"": (1,), "passed": (1,)}),
-
-
-    # A couple more complex combinations
-    ("red", "1 failed, 2 passed, 3 xfailed",
-        {"passed": (1, 2), "failed": (1,), "xfailed": (1, 2, 3)}),
-
-    ("green", "1 passed, 2 skipped, 3 deselected, 2 xfailed",
-        {"passed": (1,),
-         "skipped": (1, 2),
-         "deselected": (1, 2, 3),
-         "xfailed": (1, 2)}),
-])
+@pytest.mark.parametrize(
+    "exp_color, exp_line, stats_arg",
+    [
+        # The method under test only cares about the length of each
+        # dict value, not the actual contents, so tuples of anything
+        # suffice
+        # Important statuses -- the highest priority of these always wins
+        ("red", "1 failed", {"failed": (1,)}),
+        ("red", "1 failed, 1 passed", {"failed": (1,), "passed": (1,)}),
+        ("red", "1 error", {"error": (1,)}),
+        ("red", "1 passed, 1 error", {"error": (1,), "passed": (1,)}),
+        # (a status that's not known to the code)
+        ("yellow", "1 weird", {"weird": (1,)}),
+        ("yellow", "1 passed, 1 weird", {"weird": (1,), "passed": (1,)}),
+        ("yellow", "1 warnings", {"warnings": (1,)}),
+        ("yellow", "1 passed, 1 warnings", {"warnings": (1,), "passed": (1,)}),
+        ("green", "5 passed", {"passed": (1, 2, 3, 4, 5)}),
+        # "Boring" statuses.  These have no effect on the color of the summary
+        # line.  Thus, if *every* test has a boring status, the summary line stays
+        # at its default color, i.e. yellow, to warn the user that the test run
+        # produced no useful information
+        ("yellow", "1 skipped", {"skipped": (1,)}),
+        ("green", "1 passed, 1 skipped", {"skipped": (1,), "passed": (1,)}),
+        ("yellow", "1 deselected", {"deselected": (1,)}),
+        ("green", "1 passed, 1 deselected", {"deselected": (1,), "passed": (1,)}),
+        ("yellow", "1 xfailed", {"xfailed": (1,)}),
+        ("green", "1 passed, 1 xfailed", {"xfailed": (1,), "passed": (1,)}),
+        ("yellow", "1 xpassed", {"xpassed": (1,)}),
+        ("green", "1 passed, 1 xpassed", {"xpassed": (1,), "passed": (1,)}),
+        # Likewise if no tests were found at all
+        ("yellow", "no tests ran", {}),
+        # Test the empty-key special case
+        ("yellow", "no tests ran", {"": (1,)}),
+        ("green", "1 passed", {"": (1,), "passed": (1,)}),
+        # A couple more complex combinations
+        (
+            "red",
+            "1 failed, 2 passed, 3 xfailed",
+            {"passed": (1, 2), "failed": (1,), "xfailed": (1, 2, 3)},
+        ),
+        (
+            "green",
+            "1 passed, 2 skipped, 3 deselected, 2 xfailed",
+            {
+                "passed": (1,),
+                "skipped": (1, 2),
+                "deselected": (1, 2, 3),
+                "xfailed": (1, 2),
+            },
+        ),
+    ],
+)
 def test_summary_stats(exp_line, exp_color, stats_arg):
     print("Based on stats: %s" % stats_arg)
-    print("Expect summary: \"%s\"; with color \"%s\"" % (exp_line, exp_color))
+    print('Expect summary: "%s"; with color "%s"' % (exp_line, exp_color))
     (line, color) = build_summary_stats_line(stats_arg)
-    print("Actually got:   \"%s\"; with color \"%s\"" % (line, color))
+    print('Actually got:   "%s"; with color "%s"' % (line, color))
     assert line == exp_line
     assert color == exp_color
 
 
 def test_no_trailing_whitespace_after_inifile_word(testdir):
-    result = testdir.runpytest('')
-    assert 'inifile:\n' in result.stdout.str()
+    result = testdir.runpytest("")
+    assert "inifile:\n" in result.stdout.str()
 
-    testdir.makeini('[pytest]')
-    result = testdir.runpytest('')
-    assert 'inifile: tox.ini\n' in result.stdout.str()
+    testdir.makeini("[pytest]")
+    result = testdir.runpytest("")
+    assert "inifile: tox.ini\n" in result.stdout.str()
 
 
-class TestProgress:
+class TestProgress(object):
 
     @pytest.fixture
-    def many_tests_file(self, testdir):
+    def many_tests_files(self, testdir):
         testdir.makepyfile(
             test_bar="""
                 import pytest
                 @pytest.mark.parametrize('i', range(10))
                 def test_bar(i): pass
             """,
             test_foo="""
                 import pytest
@@ -986,54 +1121,147 @@ class TestProgress:
                 @pytest.mark.parametrize('i', range(5))
                 def test_foobar(i): pass
             """,
         )
 
     def test_zero_tests_collected(self, testdir):
         """Some plugins (testmon for example) might issue pytest_runtest_logreport without any tests being
         actually collected (#2971)."""
-        testdir.makeconftest("""
+        testdir.makeconftest(
+            """
         def pytest_collection_modifyitems(items, config):
             from _pytest.runner import CollectReport
             for node_id in ('nodeid1', 'nodeid2'):
                 rep = CollectReport(node_id, 'passed', None, None)
                 rep.when = 'passed'
                 rep.duration = 0.1
                 config.hook.pytest_runtest_logreport(report=rep)
-        """)
+        """
+        )
+        output = testdir.runpytest()
+        assert "ZeroDivisionError" not in output.stdout.str()
+        output.stdout.fnmatch_lines(["=* 2 passed in *="])
+
+    def test_normal(self, many_tests_files, testdir):
         output = testdir.runpytest()
-        assert 'ZeroDivisionError' not in output.stdout.str()
-        output.stdout.fnmatch_lines([
-            '=* 2 passed in *=',
-        ])
+        output.stdout.re_match_lines(
+            [
+                r"test_bar.py \.{10} \s+ \[ 50%\]",
+                r"test_foo.py \.{5} \s+ \[ 75%\]",
+                r"test_foobar.py \.{5} \s+ \[100%\]",
+            ]
+        )
+
+    def test_verbose(self, many_tests_files, testdir):
+        output = testdir.runpytest("-v")
+        output.stdout.re_match_lines(
+            [
+                r"test_bar.py::test_bar\[0\] PASSED \s+ \[  5%\]",
+                r"test_foo.py::test_foo\[4\] PASSED \s+ \[ 75%\]",
+                r"test_foobar.py::test_foobar\[4\] PASSED \s+ \[100%\]",
+            ]
+        )
 
-    def test_normal(self, many_tests_file, testdir):
-        output = testdir.runpytest()
-        output.stdout.re_match_lines([
-            r'test_bar.py \.{10} \s+ \[ 50%\]',
-            r'test_foo.py \.{5} \s+ \[ 75%\]',
-            r'test_foobar.py \.{5} \s+ \[100%\]',
-        ])
+    def test_xdist_normal(self, many_tests_files, testdir):
+        pytest.importorskip("xdist")
+        output = testdir.runpytest("-n2")
+        output.stdout.re_match_lines([r"\.{20} \s+ \[100%\]"])
+
+    def test_xdist_verbose(self, many_tests_files, testdir):
+        pytest.importorskip("xdist")
+        output = testdir.runpytest("-n2", "-v")
+        output.stdout.re_match_lines_random(
+            [
+                r"\[gw\d\] \[\s*\d+%\] PASSED test_bar.py::test_bar\[1\]",
+                r"\[gw\d\] \[\s*\d+%\] PASSED test_foo.py::test_foo\[1\]",
+                r"\[gw\d\] \[\s*\d+%\] PASSED test_foobar.py::test_foobar\[1\]",
+            ]
+        )
+
+    def test_capture_no(self, many_tests_files, testdir):
+        output = testdir.runpytest("-s")
+        output.stdout.re_match_lines(
+            [r"test_bar.py \.{10}", r"test_foo.py \.{5}", r"test_foobar.py \.{5}"]
+        )
+
+        output = testdir.runpytest("--capture=no")
+        assert "%]" not in output.stdout.str()
+
+
+class TestProgressWithTeardown(object):
+    """Ensure we show the correct percentages for tests that fail during teardown (#3088)"""
+
+    @pytest.fixture
+    def contest_with_teardown_fixture(self, testdir):
+        testdir.makeconftest(
+            """
+            import pytest
 
-    def test_verbose(self, many_tests_file, testdir):
-        output = testdir.runpytest('-v')
-        output.stdout.re_match_lines([
-            r'test_bar.py::test_bar\[0\] PASSED \s+ \[  5%\]',
-            r'test_foo.py::test_foo\[4\] PASSED \s+ \[ 75%\]',
-            r'test_foobar.py::test_foobar\[4\] PASSED \s+ \[100%\]',
-        ])
+            @pytest.fixture
+            def fail_teardown():
+                yield
+                assert False
+        """
+        )
+
+    @pytest.fixture
+    def many_files(self, testdir, contest_with_teardown_fixture):
+        testdir.makepyfile(
+            test_bar="""
+                import pytest
+                @pytest.mark.parametrize('i', range(5))
+                def test_bar(fail_teardown, i):
+                    pass
+            """,
+            test_foo="""
+                import pytest
+                @pytest.mark.parametrize('i', range(15))
+                def test_foo(fail_teardown, i):
+                    pass
+            """,
+        )
+
+    def test_teardown_simple(self, testdir, contest_with_teardown_fixture):
+        testdir.makepyfile(
+            """
+            def test_foo(fail_teardown):
+                pass
+        """
+        )
+        output = testdir.runpytest()
+        output.stdout.re_match_lines([r"test_teardown_simple.py \.E\s+\[100%\]"])
 
-    def test_xdist_normal(self, many_tests_file, testdir):
-        pytest.importorskip('xdist')
-        output = testdir.runpytest('-n2')
-        output.stdout.re_match_lines([
-            r'\.{20} \s+ \[100%\]',
-        ])
+    def test_teardown_with_test_also_failing(
+        self, testdir, contest_with_teardown_fixture
+    ):
+        testdir.makepyfile(
+            """
+            def test_foo(fail_teardown):
+                assert False
+        """
+        )
+        output = testdir.runpytest()
+        output.stdout.re_match_lines(
+            [r"test_teardown_with_test_also_failing.py FE\s+\[100%\]"]
+        )
 
-    def test_xdist_verbose(self, many_tests_file, testdir):
-        pytest.importorskip('xdist')
-        output = testdir.runpytest('-n2', '-v')
-        output.stdout.re_match_lines_random([
-            r'\[gw\d\] \[\s*\d+%\] PASSED test_bar.py::test_bar\[1\]',
-            r'\[gw\d\] \[\s*\d+%\] PASSED test_foo.py::test_foo\[1\]',
-            r'\[gw\d\] \[\s*\d+%\] PASSED test_foobar.py::test_foobar\[1\]',
-        ])
+    def test_teardown_many(self, testdir, many_files):
+        output = testdir.runpytest()
+        output.stdout.re_match_lines(
+            [r"test_bar.py (\.E){5}\s+\[ 25%\]", r"test_foo.py (\.E){15}\s+\[100%\]"]
+        )
+
+    def test_teardown_many_verbose(self, testdir, many_files):
+        output = testdir.runpytest("-v")
+        output.stdout.re_match_lines(
+            [
+                r"test_bar.py::test_bar\[0\] PASSED\s+\[  5%\]",
+                r"test_bar.py::test_bar\[0\] ERROR\s+\[  5%\]",
+                r"test_bar.py::test_bar\[4\] PASSED\s+\[ 25%\]",
+                r"test_bar.py::test_bar\[4\] ERROR\s+\[ 25%\]",
+            ]
+        )
+
+    def test_xdist_normal(self, many_files, testdir):
+        pytest.importorskip("xdist")
+        output = testdir.runpytest("-n2")
+        output.stdout.re_match_lines([r"[\.E]{40} \s+ \[100%\]"])
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_tmpdir.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_tmpdir.py
@@ -2,23 +2,26 @@ from __future__ import absolute_import, 
 import sys
 import py
 import pytest
 
 from _pytest.tmpdir import tmpdir
 
 
 def test_funcarg(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
             def pytest_generate_tests(metafunc):
                 metafunc.addcall(id='a')
                 metafunc.addcall(id='b')
             def test_func(tmpdir): pass
-    """)
+    """
+    )
     from _pytest.tmpdir import TempdirFactory
+
     reprec = testdir.inline_run()
     calls = reprec.getcalls("pytest_runtest_setup")
     item = calls[0].item
     config = item.config
     tmpdirhandler = TempdirFactory(config)
     item._initrequest()
     p = tmpdir(item._request, tmpdirhandler)
     assert p.check()
@@ -27,162 +30,183 @@ def test_funcarg(testdir):
     item.name = "qwe/\\abc"
     p = tmpdir(item._request, tmpdirhandler)
     assert p.check()
     bn = p.basename.strip("0123456789")
     assert bn == "qwe__abc"
 
 
 def test_ensuretemp(recwarn):
-    d1 = pytest.ensuretemp('hello')
-    d2 = pytest.ensuretemp('hello')
+    d1 = pytest.ensuretemp("hello")
+    d2 = pytest.ensuretemp("hello")
     assert d1 == d2
     assert d1.check(dir=1)
 
 
 class TestTempdirHandler(object):
+
     def test_mktemp(self, testdir):
         from _pytest.tmpdir import TempdirFactory
+
         config = testdir.parseconfig()
         config.option.basetemp = testdir.mkdir("hello")
         t = TempdirFactory(config)
         tmp = t.mktemp("world")
         assert tmp.relto(t.getbasetemp()) == "world0"
         tmp = t.mktemp("this")
         assert tmp.relto(t.getbasetemp()).startswith("this")
         tmp2 = t.mktemp("this")
         assert tmp2.relto(t.getbasetemp()).startswith("this")
         assert tmp2 != tmp
 
 
 class TestConfigTmpdir(object):
+
     def test_getbasetemp_custom_removes_old(self, testdir):
         mytemp = testdir.tmpdir.join("xyz")
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             def test_1(tmpdir):
                 pass
-        """)
-        testdir.runpytest(p, '--basetemp=%s' % mytemp)
+        """
+        )
+        testdir.runpytest(p, "--basetemp=%s" % mytemp)
         mytemp.check()
         mytemp.ensure("hello")
 
-        testdir.runpytest(p, '--basetemp=%s' % mytemp)
+        testdir.runpytest(p, "--basetemp=%s" % mytemp)
         mytemp.check()
         assert not mytemp.join("hello").check()
 
 
 def test_basetemp(testdir):
     mytemp = testdir.tmpdir.mkdir("mytemp")
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         import pytest
         def test_1():
             pytest.ensuretemp("hello")
-    """)
-    result = testdir.runpytest(p, '--basetemp=%s' % mytemp)
+    """
+    )
+    result = testdir.runpytest(p, "--basetemp=%s" % mytemp)
     assert result.ret == 0
-    assert mytemp.join('hello').check()
+    assert mytemp.join("hello").check()
 
 
-@pytest.mark.skipif(not hasattr(py.path.local, 'mksymlinkto'),
-                    reason="symlink not available on this platform")
+@pytest.mark.skipif(
+    not hasattr(py.path.local, "mksymlinkto"),
+    reason="symlink not available on this platform",
+)
 def test_tmpdir_always_is_realpath(testdir):
     # the reason why tmpdir should be a realpath is that
     # when you cd to it and do "os.getcwd()" you will anyway
     # get the realpath.  Using the symlinked path can thus
     # easily result in path-inequality
     # XXX if that proves to be a problem, consider using
     # os.environ["PWD"]
     realtemp = testdir.tmpdir.mkdir("myrealtemp")
     linktemp = testdir.tmpdir.join("symlinktemp")
     linktemp.mksymlinkto(realtemp)
-    p = testdir.makepyfile("""
+    p = testdir.makepyfile(
+        """
         def test_1(tmpdir):
             import os
             assert os.path.realpath(str(tmpdir)) == str(tmpdir)
-    """)
-    result = testdir.runpytest("-s", p, '--basetemp=%s/bt' % linktemp)
+    """
+    )
+    result = testdir.runpytest("-s", p, "--basetemp=%s/bt" % linktemp)
     assert not result.ret
 
 
 def test_tmpdir_too_long_on_parametrization(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         @pytest.mark.parametrize("arg", ["1"*1000])
         def test_some(arg, tmpdir):
             tmpdir.ensure("hello")
-    """)
+    """
+    )
     reprec = testdir.inline_run()
     reprec.assertoutcome(passed=1)
 
 
 def test_tmpdir_factory(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         @pytest.fixture(scope='session')
         def session_dir(tmpdir_factory):
             return tmpdir_factory.mktemp('data', numbered=False)
         def test_some(session_dir):
             session_dir.isdir()
-    """)
+    """
+    )
     reprec = testdir.inline_run()
     reprec.assertoutcome(passed=1)
 
 
 def test_tmpdir_fallback_tox_env(testdir, monkeypatch):
     """Test that tmpdir works even if environment variables required by getpass
     module are missing (#1010).
     """
-    monkeypatch.delenv('USER', raising=False)
-    monkeypatch.delenv('USERNAME', raising=False)
-    testdir.makepyfile("""
+    monkeypatch.delenv("USER", raising=False)
+    monkeypatch.delenv("USERNAME", raising=False)
+    testdir.makepyfile(
+        """
         import pytest
         def test_some(tmpdir):
             assert tmpdir.isdir()
-    """)
+    """
+    )
     reprec = testdir.inline_run()
     reprec.assertoutcome(passed=1)
 
 
 @pytest.fixture
 def break_getuser(monkeypatch):
-    monkeypatch.setattr('os.getuid', lambda: -1)
+    monkeypatch.setattr("os.getuid", lambda: -1)
     # taken from python 2.7/3.4
-    for envvar in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
+    for envvar in ("LOGNAME", "USER", "LNAME", "USERNAME"):
         monkeypatch.delenv(envvar, raising=False)
 
 
 @pytest.mark.usefixtures("break_getuser")
-@pytest.mark.skipif(sys.platform.startswith('win'), reason='no os.getuid on windows')
+@pytest.mark.skipif(sys.platform.startswith("win"), reason="no os.getuid on windows")
 def test_tmpdir_fallback_uid_not_found(testdir):
     """Test that tmpdir works even if the current process's user id does not
     correspond to a valid user.
     """
 
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import pytest
         def test_some(tmpdir):
             assert tmpdir.isdir()
-    """)
+    """
+    )
     reprec = testdir.inline_run()
     reprec.assertoutcome(passed=1)
 
 
 @pytest.mark.usefixtures("break_getuser")
-@pytest.mark.skipif(sys.platform.startswith('win'), reason='no os.getuid on windows')
+@pytest.mark.skipif(sys.platform.startswith("win"), reason="no os.getuid on windows")
 def test_get_user_uid_not_found():
     """Test that get_user() function works even 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'.
     """
     from _pytest.tmpdir import get_user
+
     assert get_user() is None
 
 
-@pytest.mark.skipif(not sys.platform.startswith('win'), reason='win only')
+@pytest.mark.skipif(not sys.platform.startswith("win"), reason="win only")
 def test_get_user(monkeypatch):
     """Test that get_user() function works even if environment variables
     required by getpass module are missing from the environment on Windows
     (#1010).
     """
     from _pytest.tmpdir import get_user
-    monkeypatch.delenv('USER', raising=False)
-    monkeypatch.delenv('USERNAME', raising=False)
+
+    monkeypatch.delenv("USER", raising=False)
+    monkeypatch.delenv("USERNAME", raising=False)
     assert get_user() is None
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_unittest.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_unittest.py
@@ -1,306 +1,336 @@
 from __future__ import absolute_import, division, print_function
 from _pytest.main import EXIT_NOTESTSCOLLECTED
 import pytest
 import gc
 
 
 def test_simple_unittest(testdir):
-    testpath = testdir.makepyfile("""
+    testpath = testdir.makepyfile(
+        """
         import unittest
         class MyTestCase(unittest.TestCase):
             def testpassing(self):
                 self.assertEqual('foo', 'foo')
             def test_failing(self):
                 self.assertEqual('foo', 'bar')
-    """)
+    """
+    )
     reprec = testdir.inline_run(testpath)
     assert reprec.matchreport("testpassing").passed
     assert reprec.matchreport("test_failing").failed
 
 
 def test_runTest_method(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import unittest
         class MyTestCaseWithRunTest(unittest.TestCase):
             def runTest(self):
                 self.assertEqual('foo', 'foo')
         class MyTestCaseWithoutRunTest(unittest.TestCase):
             def runTest(self):
                 self.assertEqual('foo', 'foo')
             def test_something(self):
                 pass
-        """)
+        """
+    )
     result = testdir.runpytest("-v")
-    result.stdout.fnmatch_lines("""
+    result.stdout.fnmatch_lines(
+        """
         *MyTestCaseWithRunTest::runTest*
         *MyTestCaseWithoutRunTest::test_something*
         *2 passed*
-    """)
+    """
+    )
 
 
 def test_isclasscheck_issue53(testdir):
-    testpath = testdir.makepyfile("""
+    testpath = testdir.makepyfile(
+        """
         import unittest
         class _E(object):
             def __getattr__(self, tag):
                 pass
         E = _E()
-    """)
+    """
+    )
     result = testdir.runpytest(testpath)
     assert result.ret == EXIT_NOTESTSCOLLECTED
 
 
 def test_setup(testdir):
-    testpath = testdir.makepyfile("""
+    testpath = testdir.makepyfile(
+        """
         import unittest
         class MyTestCase(unittest.TestCase):
             def setUp(self):
                 self.foo = 1
             def setup_method(self, method):
                 self.foo2 = 1
             def test_both(self):
                 self.assertEqual(1, self.foo)
                 assert self.foo2 == 1
             def teardown_method(self, method):
                 assert 0, "42"
 
-    """)
+    """
+    )
     reprec = testdir.inline_run("-s", testpath)
     assert reprec.matchreport("test_both", when="call").passed
     rep = reprec.matchreport("test_both", when="teardown")
-    assert rep.failed and '42' in str(rep.longrepr)
+    assert rep.failed and "42" in str(rep.longrepr)
 
 
 def test_setUpModule(testdir):
-    testpath = testdir.makepyfile("""
+    testpath = testdir.makepyfile(
+        """
         values = []
 
         def setUpModule():
             values.append(1)
 
         def tearDownModule():
             del values[0]
 
         def test_hello():
             assert values == [1]
 
         def test_world():
             assert values == [1]
-        """)
+        """
+    )
     result = testdir.runpytest(testpath)
-    result.stdout.fnmatch_lines([
-        "*2 passed*",
-    ])
+    result.stdout.fnmatch_lines(["*2 passed*"])
 
 
 def test_setUpModule_failing_no_teardown(testdir):
-    testpath = testdir.makepyfile("""
+    testpath = testdir.makepyfile(
+        """
         values = []
 
         def setUpModule():
             0/0
 
         def tearDownModule():
             values.append(1)
 
         def test_hello():
             pass
-    """)
+    """
+    )
     reprec = testdir.inline_run(testpath)
     reprec.assertoutcome(passed=0, failed=1)
     call = reprec.getcalls("pytest_runtest_setup")[0]
     assert not call.item.module.values
 
 
 def test_new_instances(testdir):
-    testpath = testdir.makepyfile("""
+    testpath = testdir.makepyfile(
+        """
         import unittest
         class MyTestCase(unittest.TestCase):
             def test_func1(self):
                 self.x = 2
             def test_func2(self):
                 assert not hasattr(self, 'x')
-    """)
+    """
+    )
     reprec = testdir.inline_run(testpath)
     reprec.assertoutcome(passed=2)
 
 
 def test_teardown(testdir):
-    testpath = testdir.makepyfile("""
+    testpath = testdir.makepyfile(
+        """
         import unittest
         class MyTestCase(unittest.TestCase):
             values = []
             def test_one(self):
                 pass
             def tearDown(self):
                 self.values.append(None)
         class Second(unittest.TestCase):
             def test_check(self):
                 self.assertEqual(MyTestCase.values, [None])
-    """)
+    """
+    )
     reprec = testdir.inline_run(testpath)
     passed, skipped, failed = reprec.countoutcomes()
     assert failed == 0, failed
     assert passed == 2
     assert passed + skipped + failed == 2
 
 
 def test_teardown_issue1649(testdir):
     """
     Are TestCase objects cleaned up? Often unittest TestCase objects set
     attributes that are large and expensive during setUp.
 
     The TestCase will not be cleaned up if the test fails, because it
     would then exist in the stackframe.
     """
-    testpath = testdir.makepyfile("""
+    testpath = testdir.makepyfile(
+        """
         import unittest
         class TestCaseObjectsShouldBeCleanedUp(unittest.TestCase):
             def setUp(self):
                 self.an_expensive_object = 1
             def test_demo(self):
                 pass
 
-    """)
+    """
+    )
     testdir.inline_run("-s", testpath)
     gc.collect()
     for obj in gc.get_objects():
-        assert type(obj).__name__ != 'TestCaseObjectsShouldBeCleanedUp'
+        assert type(obj).__name__ != "TestCaseObjectsShouldBeCleanedUp"
 
 
 def test_unittest_skip_issue148(testdir):
-    testpath = testdir.makepyfile("""
+    testpath = testdir.makepyfile(
+        """
         import unittest
 
         @unittest.skip("hello")
         class MyTestCase(unittest.TestCase):
             @classmethod
             def setUpClass(self):
                 xxx
             def test_one(self):
                 pass
             @classmethod
             def tearDownClass(self):
                 xxx
-    """)
+    """
+    )
     reprec = testdir.inline_run(testpath)
     reprec.assertoutcome(skipped=1)
 
 
 def test_method_and_teardown_failing_reporting(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import unittest, pytest
         class TC(unittest.TestCase):
             def tearDown(self):
                 assert 0, "down1"
             def test_method(self):
                 assert False, "down2"
-    """)
+    """
+    )
     result = testdir.runpytest("-s")
     assert result.ret == 1
-    result.stdout.fnmatch_lines([
-        "*tearDown*",
-        "*assert 0*",
-        "*test_method*",
-        "*assert False*",
-        "*1 failed*1 error*",
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*tearDown*",
+            "*assert 0*",
+            "*test_method*",
+            "*assert False*",
+            "*1 failed*1 error*",
+        ]
+    )
 
 
 def test_setup_failure_is_shown(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import unittest
         import pytest
         class TC(unittest.TestCase):
             def setUp(self):
                 assert 0, "down1"
             def test_method(self):
                 print ("never42")
                 xyz
-    """)
+    """
+    )
     result = testdir.runpytest("-s")
     assert result.ret == 1
-    result.stdout.fnmatch_lines([
-        "*setUp*",
-        "*assert 0*down1*",
-        "*1 failed*",
-    ])
-    assert 'never42' not in result.stdout.str()
+    result.stdout.fnmatch_lines(["*setUp*", "*assert 0*down1*", "*1 failed*"])
+    assert "never42" not in result.stdout.str()
 
 
 def test_setup_setUpClass(testdir):
-    testpath = testdir.makepyfile("""
+    testpath = testdir.makepyfile(
+        """
         import unittest
         import pytest
         class MyTestCase(unittest.TestCase):
             x = 0
             @classmethod
             def setUpClass(cls):
                 cls.x += 1
             def test_func1(self):
                 assert self.x == 1
             def test_func2(self):
                 assert self.x == 1
             @classmethod
             def tearDownClass(cls):
                 cls.x -= 1
         def test_teareddown():
             assert MyTestCase.x == 0
-    """)
+    """
+    )
     reprec = testdir.inline_run(testpath)
     reprec.assertoutcome(passed=3)
 
 
 def test_setup_class(testdir):
-    testpath = testdir.makepyfile("""
+    testpath = testdir.makepyfile(
+        """
         import unittest
         import pytest
         class MyTestCase(unittest.TestCase):
             x = 0
             def setup_class(cls):
                 cls.x += 1
             def test_func1(self):
                 assert self.x == 1
             def test_func2(self):
                 assert self.x == 1
             def teardown_class(cls):
                 cls.x -= 1
         def test_teareddown():
             assert MyTestCase.x == 0
-    """)
+    """
+    )
     reprec = testdir.inline_run(testpath)
     reprec.assertoutcome(passed=3)
 
 
-@pytest.mark.parametrize("type", ['Error', 'Failure'])
+@pytest.mark.parametrize("type", ["Error", "Failure"])
 def test_testcase_adderrorandfailure_defers(testdir, type):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         from unittest import TestCase
         import pytest
         class MyTestCase(TestCase):
             def run(self, result):
                 excinfo = pytest.raises(ZeroDivisionError, lambda: 0/0)
                 try:
                     result.add%s(self, excinfo._excinfo)
                 except KeyboardInterrupt:
                     raise
                 except:
                     pytest.fail("add%s should not raise")
             def test_hello(self):
                 pass
-    """ % (type, type))
+    """
+        % (type, type)
+    )
     result = testdir.runpytest()
-    assert 'should not raise' not in result.stdout.str()
+    assert "should not raise" not in result.stdout.str()
 
 
-@pytest.mark.parametrize("type", ['Error', 'Failure'])
+@pytest.mark.parametrize("type", ["Error", "Failure"])
 def test_testcase_custom_exception_info(testdir, type):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         from unittest import TestCase
         import py, pytest
         import _pytest._code
         class MyTestCase(TestCase):
             def run(self, result):
                 excinfo = pytest.raises(ZeroDivisionError, lambda: 0/0)
                 # we fake an incompatible exception info
                 from _pytest.monkeypatch import MonkeyPatch
@@ -311,79 +341,93 @@ def test_testcase_custom_exception_info(
                 mp.setattr(_pytest._code, 'ExceptionInfo', t)
                 try:
                     excinfo = excinfo._excinfo
                     result.add%(type)s(self, excinfo)
                 finally:
                     mp.undo()
             def test_hello(self):
                 pass
-    """ % locals())
+    """
+        % locals()
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        "NOTE: Incompatible Exception Representation*",
-        "*ZeroDivisionError*",
-        "*1 failed*",
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "NOTE: Incompatible Exception Representation*",
+            "*ZeroDivisionError*",
+            "*1 failed*",
+        ]
+    )
 
 
 def test_testcase_totally_incompatible_exception_info(testdir):
-    item, = testdir.getitems("""
+    item, = testdir.getitems(
+        """
         from unittest import TestCase
         class MyTestCase(TestCase):
             def test_hello(self):
                 pass
-    """)
+    """
+    )
     item.addError(None, 42)
     excinfo = item._excinfo.pop(0)
-    assert 'ERROR: Unknown Incompatible' in str(excinfo.getrepr())
+    assert "ERROR: Unknown Incompatible" in str(excinfo.getrepr())
 
 
 def test_module_level_pytestmark(testdir):
-    testpath = testdir.makepyfile("""
+    testpath = testdir.makepyfile(
+        """
         import unittest
         import pytest
         pytestmark = pytest.mark.xfail
         class MyTestCase(unittest.TestCase):
             def test_func1(self):
                 assert 0
-    """)
+    """
+    )
     reprec = testdir.inline_run(testpath, "-s")
     reprec.assertoutcome(skipped=1)
 
 
 class TestTrialUnittest(object):
+
     def setup_class(cls):
         cls.ut = pytest.importorskip("twisted.trial.unittest")
         # on windows trial uses a socket for a reactor and apparently doesn't close it properly
         # https://twistedmatrix.com/trac/ticket/9227
-        cls.ignore_unclosed_socket_warning = ('-W', 'always')
+        cls.ignore_unclosed_socket_warning = ("-W", "always")
 
     def test_trial_testcase_runtest_not_collected(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             from twisted.trial.unittest import TestCase
 
             class TC(TestCase):
                 def test_hello(self):
                     pass
-        """)
+        """
+        )
         reprec = testdir.inline_run(*self.ignore_unclosed_socket_warning)
         reprec.assertoutcome(passed=1)
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             from twisted.trial.unittest import TestCase
 
             class TC(TestCase):
                 def runTest(self):
                     pass
-        """)
+        """
+        )
         reprec = testdir.inline_run(*self.ignore_unclosed_socket_warning)
         reprec.assertoutcome(passed=1)
 
     def test_trial_exceptions_with_skips(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             from twisted.trial import unittest
             import pytest
             class TC(unittest.TestCase):
                 def test_hello(self):
                     pytest.skip("skip_in_method")
                 @pytest.mark.skipif("sys.version_info != 1")
                 def test_hello2(self):
                     pass
@@ -404,34 +448,41 @@ class TestTrialUnittest(object):
                     pass
                 test_trial_todo_success.todo = "mytodo"
 
             class TC2(unittest.TestCase):
                 def setup_class(cls):
                     pytest.skip("skip_in_setup_class")
                 def test_method(self):
                     pass
-        """)
+        """
+        )
         from _pytest.compat import _is_unittest_unexpected_success_a_failure
+
         should_fail = _is_unittest_unexpected_success_a_failure()
         result = testdir.runpytest("-rxs", *self.ignore_unclosed_socket_warning)
-        result.stdout.fnmatch_lines_random([
-            "*XFAIL*test_trial_todo*",
-            "*trialselfskip*",
-            "*skip_in_setup_class*",
-            "*iwanto*",
-            "*i2wanto*",
-            "*sys.version_info*",
-            "*skip_in_method*",
-            "*1 failed*4 skipped*3 xfailed*" if should_fail else "*4 skipped*3 xfail*1 xpass*",
-        ])
+        result.stdout.fnmatch_lines_random(
+            [
+                "*XFAIL*test_trial_todo*",
+                "*trialselfskip*",
+                "*skip_in_setup_class*",
+                "*iwanto*",
+                "*i2wanto*",
+                "*sys.version_info*",
+                "*skip_in_method*",
+                "*1 failed*4 skipped*3 xfailed*"
+                if should_fail
+                else "*4 skipped*3 xfail*1 xpass*",
+            ]
+        )
         assert result.ret == (1 if should_fail else 0)
 
     def test_trial_error(self, testdir):
-        testdir.makepyfile("""
+        testdir.makepyfile(
+            """
             from twisted.trial.unittest import TestCase
             from twisted.internet.defer import Deferred
             from twisted.internet import reactor
 
             class TC(TestCase):
                 def test_one(self):
                     crash
 
@@ -455,91 +506,107 @@ class TestTrialUnittest(object):
                         reactor.callLater(0.3, f)
                         crash
 
                     d = Deferred()
                     d.addCallback(f)
                     reactor.callLater(0.3, d.callback, None)
                     return d
                 # will crash both at test time and at teardown
-        """)
+        """
+        )
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*ERRORS*",
-            "*DelayedCalls*",
-            "*test_four*",
-            "*NameError*crash*",
-            "*test_one*",
-            "*NameError*crash*",
-            "*test_three*",
-            "*DelayedCalls*",
-            "*test_two*",
-            "*crash*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*ERRORS*",
+                "*DelayedCalls*",
+                "*test_four*",
+                "*NameError*crash*",
+                "*test_one*",
+                "*NameError*crash*",
+                "*test_three*",
+                "*DelayedCalls*",
+                "*test_two*",
+                "*crash*",
+            ]
+        )
 
     def test_trial_pdb(self, testdir):
-        p = testdir.makepyfile("""
+        p = testdir.makepyfile(
+            """
             from twisted.trial import unittest
             import pytest
             class TC(unittest.TestCase):
                 def test_hello(self):
                     assert 0, "hellopdb"
-        """)
+        """
+        )
         child = testdir.spawn_pytest(p)
         child.expect("hellopdb")
         child.sendeof()
 
     def test_trial_testcase_skip_property(self, testdir):
-        testpath = testdir.makepyfile("""
+        testpath = testdir.makepyfile(
+            """
             from twisted.trial import unittest
             class MyTestCase(unittest.TestCase):
                 skip = 'dont run'
                 def test_func(self):
                     pass
-            """)
+            """
+        )
         reprec = testdir.inline_run(testpath, "-s")
         reprec.assertoutcome(skipped=1)
 
     def test_trial_testfunction_skip_property(self, testdir):
-        testpath = testdir.makepyfile("""
+        testpath = testdir.makepyfile(
+            """
             from twisted.trial import unittest
             class MyTestCase(unittest.TestCase):
                 def test_func(self):
                     pass
                 test_func.skip = 'dont run'
-            """)
+            """
+        )
         reprec = testdir.inline_run(testpath, "-s")
         reprec.assertoutcome(skipped=1)
 
     def test_trial_testcase_todo_property(self, testdir):
-        testpath = testdir.makepyfile("""
+        testpath = testdir.makepyfile(
+            """
             from twisted.trial import unittest
             class MyTestCase(unittest.TestCase):
                 todo = 'dont run'
                 def test_func(self):
                     assert 0
-            """)
+            """
+        )
         reprec = testdir.inline_run(testpath, "-s")
         reprec.assertoutcome(skipped=1)
 
     def test_trial_testfunction_todo_property(self, testdir):
-        testpath = testdir.makepyfile("""
+        testpath = testdir.makepyfile(
+            """
             from twisted.trial import unittest
             class MyTestCase(unittest.TestCase):
                 def test_func(self):
                     assert 0
                 test_func.todo = 'dont run'
-            """)
-        reprec = testdir.inline_run(testpath, "-s", *self.ignore_unclosed_socket_warning)
+            """
+        )
+        reprec = testdir.inline_run(
+            testpath, "-s", *self.ignore_unclosed_socket_warning
+        )
         reprec.assertoutcome(skipped=1)
 
 
 def test_djangolike_testcase(testdir):
     # contributed from Morten Breekevold
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         from unittest import TestCase, main
 
         class DjangoLikeTestCase(TestCase):
 
             def setUp(self):
                 print ("setUp()")
 
             def test_presetup_has_been_run(self):
@@ -569,131 +636,140 @@ def test_djangolike_testcase(testdir):
                     return
 
             def _pre_setup(self):
                 print ("_pre_setup()")
                 self.was_presetup = True
 
             def _post_teardown(self):
                 print ("_post_teardown()")
-    """)
+    """
+    )
     result = testdir.runpytest("-s")
     assert result.ret == 0
-    result.stdout.fnmatch_lines([
-        "*_pre_setup()*",
-        "*setUp()*",
-        "*test_thing()*",
-        "*tearDown()*",
-        "*_post_teardown()*",
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*_pre_setup()*",
+            "*setUp()*",
+            "*test_thing()*",
+            "*tearDown()*",
+            "*_post_teardown()*",
+        ]
+    )
 
 
 def test_unittest_not_shown_in_traceback(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import unittest
         class t(unittest.TestCase):
             def test_hello(self):
                 x = 3
                 self.assertEqual(x, 4)
-    """)
+    """
+    )
     res = testdir.runpytest()
     assert "failUnlessEqual" not in res.stdout.str()
 
 
 def test_unorderable_types(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import unittest
         class TestJoinEmpty(unittest.TestCase):
             pass
 
         def make_test():
             class Test(unittest.TestCase):
                 pass
             Test.__name__ = "TestFoo"
             return Test
         TestFoo = make_test()
-    """)
+    """
+    )
     result = testdir.runpytest()
     assert "TypeError" not in result.stdout.str()
     assert result.ret == EXIT_NOTESTSCOLLECTED
 
 
 def test_unittest_typerror_traceback(testdir):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import unittest
         class TestJoinEmpty(unittest.TestCase):
             def test_hello(self, arg1):
                 pass
-    """)
+    """
+    )
     result = testdir.runpytest()
     assert "TypeError" in result.stdout.str()
     assert result.ret == 1
 
 
-@pytest.mark.parametrize('runner', ['pytest', 'unittest'])
+@pytest.mark.parametrize("runner", ["pytest", "unittest"])
 def test_unittest_expected_failure_for_failing_test_is_xfail(testdir, runner):
-    script = testdir.makepyfile("""
+    script = testdir.makepyfile(
+        """
         import unittest
         class MyTestCase(unittest.TestCase):
             @unittest.expectedFailure
             def test_failing_test_is_xfail(self):
                 assert False
         if __name__ == '__main__':
             unittest.main()
-    """)
-    if runner == 'pytest':
+    """
+    )
+    if runner == "pytest":
         result = testdir.runpytest("-rxX")
-        result.stdout.fnmatch_lines([
-            "*XFAIL*MyTestCase*test_failing_test_is_xfail*",
-            "*1 xfailed*",
-        ])
+        result.stdout.fnmatch_lines(
+            ["*XFAIL*MyTestCase*test_failing_test_is_xfail*", "*1 xfailed*"]
+        )
     else:
         result = testdir.runpython(script)
-        result.stderr.fnmatch_lines([
-            "*1 test in*",
-            "*OK*(expected failures=1)*",
-        ])
+        result.stderr.fnmatch_lines(["*1 test in*", "*OK*(expected failures=1)*"])
     assert result.ret == 0
 
 
-@pytest.mark.parametrize('runner', ['pytest', 'unittest'])
+@pytest.mark.parametrize("runner", ["pytest", "unittest"])
 def test_unittest_expected_failure_for_passing_test_is_fail(testdir, runner):
-    script = testdir.makepyfile("""
+    script = testdir.makepyfile(
+        """
         import unittest
         class MyTestCase(unittest.TestCase):
             @unittest.expectedFailure
             def test_passing_test_is_fail(self):
                 assert True
         if __name__ == '__main__':
             unittest.main()
-    """)
+    """
+    )
     from _pytest.compat import _is_unittest_unexpected_success_a_failure
+
     should_fail = _is_unittest_unexpected_success_a_failure()
-    if runner == 'pytest':
+    if runner == "pytest":
         result = testdir.runpytest("-rxX")
-        result.stdout.fnmatch_lines([
-            "*MyTestCase*test_passing_test_is_fail*",
-            "*1 failed*" if should_fail else "*1 xpassed*",
-        ])
+        result.stdout.fnmatch_lines(
+            [
+                "*MyTestCase*test_passing_test_is_fail*",
+                "*1 failed*" if should_fail else "*1 xpassed*",
+            ]
+        )
     else:
         result = testdir.runpython(script)
-        result.stderr.fnmatch_lines([
-            "*1 test in*",
-            "*(unexpected successes=1)*",
-        ])
+        result.stderr.fnmatch_lines(["*1 test in*", "*(unexpected successes=1)*"])
 
     assert result.ret == (1 if should_fail else 0)
 
 
-@pytest.mark.parametrize('fix_type, stmt', [
-    ('fixture', 'return'),
-    ('yield_fixture', 'yield'),
-])
+@pytest.mark.parametrize(
+    "fix_type, stmt", [("fixture", "return"), ("yield_fixture", "yield")]
+)
 def test_unittest_setup_interaction(testdir, fix_type, stmt):
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import unittest
         import pytest
         class MyTestCase(unittest.TestCase):
             @pytest.{fix_type}(scope="class", autouse=True)
             def perclass(self, request):
                 request.cls.hello = "world"
                 {stmt}
             @pytest.{fix_type}(scope="function", autouse=True)
@@ -705,23 +781,27 @@ def test_unittest_setup_interaction(test
                 assert self.funcname == "test_method1"
                 assert self.hello == "world"
 
             def test_method2(self):
                 assert self.funcname == "test_method2"
 
             def test_classattr(self):
                 assert self.__class__.hello == "world"
-    """.format(fix_type=fix_type, stmt=stmt))
+    """.format(
+            fix_type=fix_type, stmt=stmt
+        )
+    )
     result = testdir.runpytest()
     result.stdout.fnmatch_lines("*3 passed*")
 
 
 def test_non_unittest_no_setupclass_support(testdir):
-    testpath = testdir.makepyfile("""
+    testpath = testdir.makepyfile(
+        """
         class TestFoo(object):
             x = 0
 
             @classmethod
             def setUpClass(cls):
                 cls.x = 1
 
             def test_method1(self):
@@ -729,23 +809,25 @@ def test_non_unittest_no_setupclass_supp
 
             @classmethod
             def tearDownClass(cls):
                 cls.x = 1
 
         def test_not_teareddown():
             assert TestFoo.x == 0
 
-    """)
+    """
+    )
     reprec = testdir.inline_run(testpath)
     reprec.assertoutcome(passed=2)
 
 
 def test_no_teardown_if_setupclass_failed(testdir):
-    testpath = testdir.makepyfile("""
+    testpath = testdir.makepyfile(
+        """
         import unittest
 
         class MyTestCase(unittest.TestCase):
             x = 0
 
             @classmethod
             def setUpClass(cls):
                 cls.x = 1
@@ -755,76 +837,156 @@ def test_no_teardown_if_setupclass_faile
                 cls.x = 10
 
             @classmethod
             def tearDownClass(cls):
                 cls.x = 100
 
         def test_notTornDown():
             assert MyTestCase.x == 1
-    """)
+    """
+    )
     reprec = testdir.inline_run(testpath)
     reprec.assertoutcome(passed=1, failed=1)
 
 
 def test_issue333_result_clearing(testdir):
-    testdir.makeconftest("""
+    testdir.makeconftest(
+        """
         import pytest
         @pytest.hookimpl(hookwrapper=True)
         def pytest_runtest_call(item):
             yield
             assert 0
-    """)
-    testdir.makepyfile("""
+    """
+    )
+    testdir.makepyfile(
+        """
         import unittest
         class TestIt(unittest.TestCase):
             def test_func(self):
                 0/0
-    """)
+    """
+    )
 
     reprec = testdir.inline_run()
     reprec.assertoutcome(failed=1)
 
 
 def test_unittest_raise_skip_issue748(testdir):
-    testdir.makepyfile(test_foo="""
+    testdir.makepyfile(
+        test_foo="""
         import unittest
 
         class MyTestCase(unittest.TestCase):
             def test_one(self):
                 raise unittest.SkipTest('skipping due to reasons')
-    """)
-    result = testdir.runpytest("-v", '-rs')
-    result.stdout.fnmatch_lines("""
+    """
+    )
+    result = testdir.runpytest("-v", "-rs")
+    result.stdout.fnmatch_lines(
+        """
         *SKIP*[1]*test_foo.py*skipping due to reasons*
         *1 skipped*
-    """)
+    """
+    )
 
 
 def test_unittest_skip_issue1169(testdir):
-    testdir.makepyfile(test_foo="""
+    testdir.makepyfile(
+        test_foo="""
         import unittest
 
         class MyTestCase(unittest.TestCase):
             @unittest.skip("skipping due to reasons")
             def test_skip(self):
                  self.fail()
-        """)
-    result = testdir.runpytest("-v", '-rs')
-    result.stdout.fnmatch_lines("""
+        """
+    )
+    result = testdir.runpytest("-v", "-rs")
+    result.stdout.fnmatch_lines(
+        """
         *SKIP*[1]*skipping due to reasons*
         *1 skipped*
-    """)
+    """
+    )
 
 
 def test_class_method_containing_test_issue1558(testdir):
-    testdir.makepyfile(test_foo="""
+    testdir.makepyfile(
+        test_foo="""
         import unittest
 
         class MyTestCase(unittest.TestCase):
             def test_should_run(self):
                 pass
             def test_should_not_run(self):
                 pass
             test_should_not_run.__test__ = False
-    """)
+    """
+    )
     reprec = testdir.inline_run()
     reprec.assertoutcome(passed=1)
+
+
+@pytest.mark.issue(3498)
+@pytest.mark.parametrize(
+    "base", ["six.moves.builtins.object", "unittest.TestCase", "unittest2.TestCase"]
+)
+def test_usefixtures_marker_on_unittest(base, testdir):
+    module = base.rsplit(".", 1)[0]
+    pytest.importorskip(module)
+    testdir.makepyfile(
+        conftest="""
+        import pytest
+
+        @pytest.fixture(scope='function')
+        def fixture1(request, monkeypatch):
+            monkeypatch.setattr(request.instance, 'fixture1', True )
+
+
+        @pytest.fixture(scope='function')
+        def fixture2(request, monkeypatch):
+            monkeypatch.setattr(request.instance, 'fixture2', True )
+
+        def node_and_marks(item):
+            print(item.nodeid)
+            for mark in item.iter_markers():
+                print("  ", mark)
+
+        @pytest.fixture(autouse=True)
+        def my_marks(request):
+            node_and_marks(request.node)
+
+        def pytest_collection_modifyitems(items):
+            for item in items:
+               node_and_marks(item)
+
+        """
+    )
+
+    testdir.makepyfile(
+        """
+        import pytest
+        import {module}
+
+        class Tests({base}):
+            fixture1 = False
+            fixture2 = False
+
+            @pytest.mark.usefixtures("fixture1")
+            def test_one(self):
+                assert self.fixture1
+                assert not self.fixture2
+
+            @pytest.mark.usefixtures("fixture1", "fixture2")
+            def test_two(self):
+                assert self.fixture1
+                assert self.fixture2
+
+
+    """.format(
+            module=module, base=base
+        )
+    )
+
+    result = testdir.runpytest("-s")
+    result.assert_outcomes(passed=2)
--- a/testing/web-platform/tests/tools/third_party/pytest/testing/test_warnings.py
+++ b/testing/web-platform/tests/tools/third_party/pytest/testing/test_warnings.py
@@ -1,258 +1,290 @@
 # -*- coding: utf8 -*-
 from __future__ import unicode_literals
 
 import sys
 
 import pytest
 
 
-WARNINGS_SUMMARY_HEADER = 'warnings summary'
+WARNINGS_SUMMARY_HEADER = "warnings summary"
 
 
 @pytest.fixture
 def pyfile_with_warnings(testdir, request):
     """
     Create a test file which calls a function in a module which generates warnings.
     """
     testdir.syspathinsert()
     test_name = request.function.__name__
-    module_name = test_name.lstrip('test_') + '_module'
-    testdir.makepyfile(**{
-        module_name: '''
+    module_name = test_name.lstrip("test_") + "_module"
+    testdir.makepyfile(
+        **{
+            module_name: """
             import warnings
             def foo():
                 warnings.warn(UserWarning("user warning"))
                 warnings.warn(RuntimeWarning("runtime warning"))
                 return 1
-        ''',
-        test_name: '''
+        """,
+            test_name: """
             import {module_name}
             def test_func():
                 assert {module_name}.foo() == 1
-        '''.format(module_name=module_name)
-    })
+        """.format(
+                module_name=module_name
+            ),
+        }
+    )
 
 
-@pytest.mark.filterwarnings('always')
+@pytest.mark.filterwarnings("always")
 def test_normal_flow(testdir, pyfile_with_warnings):
     """
     Check that the warnings section is displayed, containing test node ids followed by
     all warnings generated by that test node.
     """
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        '*== %s ==*' % WARNINGS_SUMMARY_HEADER,
-
-        '*test_normal_flow.py::test_func',
-
-        '*normal_flow_module.py:3: UserWarning: user warning',
-        '*  warnings.warn(UserWarning("user warning"))',
-
-        '*normal_flow_module.py:4: RuntimeWarning: runtime warning',
-        '*  warnings.warn(RuntimeWarning("runtime warning"))',
-        '* 1 passed, 2 warnings*',
-    ])
-    assert result.stdout.str().count('test_normal_flow.py::test_func') == 1
+    result.stdout.fnmatch_lines(
+        [
+            "*== %s ==*" % WARNINGS_SUMMARY_HEADER,
+            "*test_normal_flow.py::test_func",
+            "*normal_flow_module.py:3: UserWarning: user warning",
+            '*  warnings.warn(UserWarning("user warning"))',
+            "*normal_flow_module.py:4: RuntimeWarning: runtime warning",
+            '*  warnings.warn(RuntimeWarning("runtime warning"))',
+            "* 1 passed, 2 warnings*",
+        ]
+    )
+    assert result.stdout.str().count("test_normal_flow.py::test_func") == 1
 
 
-@pytest.mark.filterwarnings('always')
+@pytest.mark.filterwarnings("always")
 def test_setup_teardown_warnings(testdir, pyfile_with_warnings):
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         import warnings
         import pytest
 
         @pytest.fixture
         def fix():
             warnings.warn(UserWarning("warning during setup"))
             yield
             warnings.warn(UserWarning("warning during teardown"))
 
         def test_func(fix):
             pass
-    ''')
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        '*== %s ==*' % WARNINGS_SUMMARY_HEADER,
-
-        '*test_setup_teardown_warnings.py:6: UserWarning: warning during setup',
-        '*warnings.warn(UserWarning("warning during setup"))',
-
-        '*test_setup_teardown_warnings.py:8: UserWarning: warning during teardown',
-        '*warnings.warn(UserWarning("warning during teardown"))',
-        '* 1 passed, 2 warnings*',
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*== %s ==*" % WARNINGS_SUMMARY_HEADER,
+            "*test_setup_teardown_warnings.py:6: UserWarning: warning during setup",
+            '*warnings.warn(UserWarning("warning during setup"))',
+            "*test_setup_teardown_warnings.py:8: UserWarning: warning during teardown",
+            '*warnings.warn(UserWarning("warning during teardown"))',
+            "* 1 passed, 2 warnings*",
+        ]
+    )
 
 
-@pytest.mark.parametrize('method', ['cmdline', 'ini'])
+@pytest.mark.parametrize("method", ["cmdline", "ini"])
 def test_as_errors(testdir, pyfile_with_warnings, method):
-    args = ('-W', 'error') if method == 'cmdline' else ()
-    if method == 'ini':
-        testdir.makeini('''
+    args = ("-W", "error") if method == "cmdline" else ()
+    if method == "ini":
+        testdir.makeini(
+            """
             [pytest]
             filterwarnings= error
-            ''')
+            """
+        )
     result = testdir.runpytest(*args)
-    result.stdout.fnmatch_lines([
-        'E       UserWarning: user warning',
-        'as_errors_module.py:3: UserWarning',
-        '* 1 failed in *',
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "E       UserWarning: user warning",
+            "as_errors_module.py:3: UserWarning",
+            "* 1 failed in *",
+        ]
+    )
 
 
-@pytest.mark.parametrize('method', ['cmdline', 'ini'])
+@pytest.mark.parametrize("method", ["cmdline", "ini"])
 def test_ignore(testdir, pyfile_with_warnings, method):
-    args = ('-W', 'ignore') if method == 'cmdline' else ()
-    if method == 'ini':
-        testdir.makeini('''
+    args = ("-W", "ignore") if method == "cmdline" else ()
+    if method == "ini":
+        testdir.makeini(
+            """
         [pytest]
         filterwarnings= ignore
-        ''')
+        """
+        )
 
     result = testdir.runpytest(*args)
-    result.stdout.fnmatch_lines([
-        '* 1 passed in *',
-    ])
+    result.stdout.fnmatch_lines(["* 1 passed in *"])
     assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()
 
 
-@pytest.mark.skipif(sys.version_info < (3, 0),
-                    reason='warnings message is unicode is ok in python3')
-@pytest.mark.filterwarnings('always')
+@pytest.mark.skipif(
+    sys.version_info < (3, 0), reason="warnings message is unicode is ok in python3"
+)
+@pytest.mark.filterwarnings("always")
 def test_unicode(testdir, pyfile_with_warnings):
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         # -*- coding: utf8 -*-
         import warnings
         import pytest
 
 
         @pytest.fixture
         def fix():
             warnings.warn(u"测试")
             yield
 
         def test_func(fix):
             pass
-    ''')
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        '*== %s ==*' % WARNINGS_SUMMARY_HEADER,
-        '*test_unicode.py:8: UserWarning: \u6d4b\u8bd5*',
-        '* 1 passed, 1 warnings*',
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*== %s ==*" % WARNINGS_SUMMARY_HEADER,
+            "*test_unicode.py:8: UserWarning: \u6d4b\u8bd5*",
+            "* 1 passed, 1 warnings*",
+        ]
+    )
 
 
-@pytest.mark.skipif(sys.version_info >= (3, 0),
-                    reason='warnings message is broken as it is not str instance')
+@pytest.mark.skipif(
+    sys.version_info >= (3, 0),
+    reason="warnings message is broken as it is not str instance",
+)
 def test_py2_unicode(testdir, pyfile_with_warnings):
-    if getattr(sys, "pypy_version_info", ())[:2] == (5, 9) and sys.platform.startswith('win'):
+    if (
+        getattr(sys, "pypy_version_info", ())[:2] == (5, 9)
+        and sys.platform.startswith("win")
+    ):
         pytest.xfail("fails with unicode error on PyPy2 5.9 and Windows (#2905)")
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         # -*- coding: utf8 -*-
         import warnings
         import pytest
 
 
         @pytest.fixture
         def fix():
             warnings.warn(u"测试")
             yield
 
         @pytest.mark.filterwarnings('always')
         def test_func(fix):
             pass
-    ''')
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        '*== %s ==*' % WARNINGS_SUMMARY_HEADER,
-
-        '*test_py2_unicode.py:8: UserWarning: \\u6d4b\\u8bd5',
-        '*warnings.warn(u"\u6d4b\u8bd5")',
-        '*warnings.py:*: UnicodeWarning: Warning is using unicode non*',
-        '* 1 passed, 2 warnings*',
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*== %s ==*" % WARNINGS_SUMMARY_HEADER,
+            "*test_py2_unicode.py:8: UserWarning: \\u6d4b\\u8bd5",
+            '*warnings.warn(u"\u6d4b\u8bd5")',
+            "*warnings.py:*: UnicodeWarning: Warning is using unicode non*",
+            "* 1 passed, 2 warnings*",
+        ]
+    )
 
 
 def test_py2_unicode_ascii(testdir):
     """Ensure that our warning about 'unicode warnings containing non-ascii messages'
     does not trigger with ascii-convertible messages"""
-    testdir.makeini('[pytest]')
-    testdir.makepyfile('''
+    testdir.makeini("[pytest]")
+    testdir.makepyfile(
+        """
         import pytest
         import warnings
 
         @pytest.mark.filterwarnings('always')
         def test_func():
             warnings.warn(u"hello")
-    ''')
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        '*== %s ==*' % WARNINGS_SUMMARY_HEADER,
-        '*warnings.warn(u"hello")',
-        '* 1 passed, 1 warnings in*'
-    ])
+    result.stdout.fnmatch_lines(
+        [
+            "*== %s ==*" % WARNINGS_SUMMARY_HEADER,
+            '*warnings.warn(u"hello")',
+            "* 1 passed, 1 warnings in*",
+        ]
+    )
 
 
 def test_works_with_filterwarnings(testdir):
     """Ensure our warnings capture does not mess with pre-installed filters (#2430)."""
-    testdir.makepyfile('''
+    testdir.makepyfile(
+        """
         import warnings
 
         class MyWarning(Warning):
             pass
 
         warnings.filterwarnings("error", category=MyWarning)
 
         class TestWarnings(object):
             def test_my_warning(self):
                 try:
                     warnings.warn(MyWarning("warn!"))
                     assert False
                 except MyWarning:
                     assert True
-    ''')
+    """
+    )
     result = testdir.runpytest()
-    result.stdout.fnmatch_lines([
-        '*== 1 passed in *',
-    ])
+    result.stdout.fnmatch_lines(["*== 1 passed in *"])
 
 
-@pytest.mark.parametrize('default_config', ['ini', 'cmdline'])
+@pytest.mark.parametrize("default_config", ["ini", "cmdline"])
 def test_filterwarnings_mark(testdir, default_config):
     """
     Test ``filterwarnings`` mark works and takes precedence over command line and ini options.
     """
-    if default_config == 'ini':
-        testdir.makeini("""
+    if default_config == "ini":
+        testdir.makeini(
+            """
             [pytest]
             filterwarnings = always
-        """)
-    testdir.makepyfile("""
+        """
+        )
+    testdir.makepyfile(
+        """
         import warnings
         import pytest
 
         @pytest.mark.filterwarnings('ignore::RuntimeWarning')
         def test_ignore_runtime_warning():
             warnings.warn(RuntimeWarning())
 
         @pytest.mark.filterwarnings('error')
         def test_warning_error():
             warnings.warn(RuntimeWarning())
 
         def test_show_warning():
             warnings.warn(RuntimeWarning())
-    """)
-    result = testdir.runpytest('-W always' if default_config == 'cmdline' else '')
-    result.stdout.fnmatch_lines(['*= 1 failed, 2 passed, 1 warnings in *'])
+    """
+    )
+    result = testdir.runpytest("-W always" if default_config == "cmdline" else "")
+    result.stdout.fnmatch_lines(["*= 1 failed, 2 passed, 1 warnings in *"])
 
 
 def test_non_string_warning_argument(testdir):
     """Non-str argument passed to warning breaks pytest (#2956)"""
-    testdir.makepyfile("""
+    testdir.makepyfile(
+        """
         import warnings
         import pytest
 
         def test():
             warnings.warn(UserWarning(1, u'foo'))
-    """)
-    result = testdir.runpytest('-W', 'always')
-    result.stdout.fnmatch_lines(['*= 1 passed, 1 warnings in *'])
+    """
+    )
+    result = testdir.runpytest("-W", "always")
+    result.stdout.fnmatch_lines(["*= 1 passed, 1 warnings in *"])
--- a/testing/web-platform/tests/tools/third_party/pytest/tox.ini
+++ b/testing/web-platform/tests/tools/third_party/pytest/tox.ini
@@ -8,24 +8,24 @@ envlist =
     py34
     py35
     py36
     py37
     pypy
     {py27,py36}-{pexpect,xdist,trial,numpy,pluggymaster}
     py27-nobyte
     doctesting
-    py35-freeze
+    py36-freeze
     docs
 
 [testenv]
 commands = pytest --lsof -ra {posargs:testing}
 passenv = USER USERNAME
 deps =
-    hypothesis>=3.5.2
+    hypothesis>=3.56
     nose
     mock
     requests
 
 [testenv:py27-subprocess]
 changedir = .
 deps =
     pytest-xdist>=1.13
@@ -33,117 +33,107 @@ deps =
     nose
 commands =
     pytest -n3 -ra --runpytest=subprocess {posargs:testing}
 
 
 [testenv:linting]
 skipsdist = True
 usedevelop = True
-basepython = python2.7
-deps =
-    flake8
-    # pygments required by rst-lint
-    pygments
-    restructuredtext_lint
-commands =
-    flake8 pytest.py _pytest testing setup.py pytest.py
-    {envpython} scripts/check-rst.py
+basepython = python3.6
+deps = pre-commit
+commands = pre-commit run --all-files --show-diff-on-failure
 
 [testenv:py27-xdist]
 deps =
     pytest-xdist>=1.13
     mock
     nose
-    hypothesis>=3.5.2
+    hypothesis>=3.56
 changedir=testing
 commands =
-    pytest -n1 -ra {posargs:.}
+    pytest -n8 -ra {posargs:.}
 
 [testenv:py36-xdist]
 deps = {[testenv:py27-xdist]deps}
-commands =
-    pytest -n3 -ra {posargs:testing}
+commands = {[testenv:py27-xdist]commands}
 
 [testenv:py27-pexpect]
 changedir = testing
 platform = linux|darwin
 deps = pexpect
 commands =
     pytest -ra test_pdb.py test_terminal.py test_unittest.py
 
 [testenv:py36-pexpect]
-changedir = testing
-platform = linux|darwin
+changedir = {[testenv:py27-pexpect]changedir}
+platform = {[testenv:py27-pexpect]platform}
 deps = {[testenv:py27-pexpect]deps}
-commands =
-    pytest -ra test_pdb.py test_terminal.py test_unittest.py
+commands = {[testenv:py27-pexpect]commands}
 
 [testenv:py27-nobyte]
 deps =
     pytest-xdist>=1.13
-    hypothesis>=3.5.2
+    hypothesis>=3.56
+    mock
 distribute = true
 changedir=testing
 setenv =
     PYTHONDONTWRITEBYTECODE=1
 commands =
     pytest -n3 -ra {posargs:.}
 
 [testenv:py27-trial]
 deps = twisted
 commands =
     pytest -ra {posargs:testing/test_unittest.py}
 
 [testenv:py36-trial]
 deps = {[testenv:py27-trial]deps}
-commands =
-    pytest -ra {posargs:testing/test_unittest.py}
+commands = {[testenv:py27-trial]commands}
 
 [testenv:py27-numpy]
-deps=numpy
+deps = numpy
 commands=
   pytest -ra {posargs:testing/python/approx.py}
 
 [testenv:py36-numpy]
-deps=numpy
-commands=
-  pytest -ra {posargs:testing/python/approx.py}
+deps = {[testenv:py27-numpy]deps}
+commands = {[testenv:py27-numpy]commands}
 
 [testenv:py27-pluggymaster]
 setenv=
     _PYTEST_SETUP_SKIP_PLUGGY_DEP=1
 deps =
     {[testenv]deps}
     git+https://github.com/pytest-dev/pluggy.git@master
 
-[testenv:py35-pluggymaster]
-setenv=
-    _PYTEST_SETUP_SKIP_PLUGGY_DEP=1
-deps =
-    {[testenv:py27-pluggymaster]deps}
-    git+https://github.com/pytest-dev/pluggy.git@master
+[testenv:py36-pluggymaster]
+setenv = {[testenv:py27-pluggymaster]setenv}
+deps = {[testenv:py27-pluggymaster]deps}
 
 [testenv:docs]
 skipsdist = True
 usedevelop = True
-basepython = python
 changedir = doc/en
 deps =
+    attrs
+    more-itertools
+    PyYAML
     sphinx
-    PyYAML
+    sphinxcontrib-trio
 
 commands =
     sphinx-build -W -b html . _build
 
 [testenv:doctesting]
 basepython = python
 usedevelop = True
 skipsdist = True
-# ensure the given pyargs cant mean anytrhing else
+# ensure the given pyargs can't mean anything else
 changedir = doc/
 deps =
     PyYAML
 commands =
     pytest -ra en
     pytest --doctest-modules --pyargs _pytest
 
 [testenv:regen]
@@ -169,17 +159,17 @@ deps =
 commands =
     autopep8 --in-place -r --max-line-length=120 --exclude=test_source_multiline_block.py _pytest testing setup.py pytest.py
 
 [testenv:jython]
 changedir = testing
 commands =
     {envpython} {envbindir}/py.test-jython -ra {posargs}
 
-[testenv:py35-freeze]
+[testenv:py36-freeze]
 changedir = testing/freeze
 deps = pyinstaller
 commands =
     {envpython} create_executable.py
     {envpython} tox_run.py
 
 
 [testenv:coveralls]
@@ -192,17 +182,16 @@ deps =
 commands =
     coverage run --source=_pytest -m pytest testing
     coverage report -m
     coveralls
 
 [pytest]
 minversion = 2.0
 plugins = pytester
-#--pyargs --doctest-modules --ignore=.tox
 addopts = -ra -p pytester --ignore=testing/cx_freeze
 rsyncdirs = tox.ini pytest.py _pytest testing
 python_files = test_*.py *_test.py testing/*/*.py
 python_classes = Test Acceptance
 python_functions = test
 norecursedirs = .tox ja .hg cx_freeze_source
 xfail_strict=true
 filterwarnings =
@@ -210,11 +199,14 @@ filterwarnings =
     # produced by path.local
     ignore:bad escape.*:DeprecationWarning:re
     # produced by path.readlines
     ignore:.*U.*mode is deprecated:DeprecationWarning
     # produced by pytest-xdist
     ignore:.*type argument to addoption.*:DeprecationWarning
     # produced by python >=3.5 on execnet (pytest-xdist)
     ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning
+    # ignore warning about package resolution using __spec__ or __package__
+    # should be a temporary solution, see #3061 for discussion
+    ignore:.*can't resolve package from __spec__ or __package__.*:ImportWarning
 
 [flake8]
 max-line-length = 120