Skip to content

Commit

Permalink
Merge pull request #3528 from asottile/blacken_docs
Browse files Browse the repository at this point in the history
blacken docs
  • Loading branch information
RonnyPfannschmidt authored Jun 3, 2018
2 parents 4dc5f78 + 0f2d7dc commit d609b63
Show file tree
Hide file tree
Showing 19 changed files with 228 additions and 130 deletions.
12 changes: 9 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,15 @@ repos:
- repo: https://github.com/ambv/black
rev: 18.4a4
hooks:
- id: black
args: [--safe, --quiet]
python_version: python3.6
- 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:
Expand Down
1 change: 1 addition & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ An example of a simple test:
def inc(x):
return x + 1
def test_answer():
assert inc(3) == 5
Expand Down
2 changes: 1 addition & 1 deletion doc/en/bash-completion.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Install argcomplete using::

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::

Expand Down
8 changes: 4 additions & 4 deletions doc/en/capture.rst
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ an example test function that performs some output related checks:

.. code-block:: python
def test_myoutput(capsys): # or use "capfd" for fd-level
def test_myoutput(capsys): # or use "capfd" for fd-level
print("hello")
sys.stderr.write("world\n")
captured = capsys.readouterr()
Expand Down Expand Up @@ -145,9 +145,9 @@ 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
10 changes: 7 additions & 3 deletions doc/en/example/attic.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,18 @@ example: specifying and selecting acceptance tests
# ./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)

Expand Down Expand Up @@ -61,6 +64,7 @@ extend the `accept example`_ by putting this in our test module:
arg.tmpdir.mkdir("special")
return arg


class TestSpecialAcceptance(object):
def test_sometest(self, accept):
assert accept.tmpdir.join("special").check()
Expand Down
80 changes: 62 additions & 18 deletions doc/en/example/simple.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ Here is a basic pattern to achieve this:
# 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
Expand All @@ -32,9 +32,12 @@ provide the ``cmdopt`` through a :ref:`fixture function <fixture function>`:
# 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):
Expand Down Expand Up @@ -102,9 +105,12 @@ the command line arguments before they get processed:
# content of conftest.py
import sys
def pytest_load_initial_conftests(args):
if 'xdist' in sys.modules: # pytest-xdist plugin
if "xdist" in sys.modules: # pytest-xdist plugin
import multiprocessing
num = max(multiprocessing.cpu_count() / 2, 1)
args[:] = ["-n", str(num)] + args
Expand Down Expand Up @@ -136,9 +142,13 @@ line option to control skipping of ``pytest.mark.slow`` marked tests:
# 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"):
Expand Down Expand Up @@ -206,10 +216,13 @@ Example:
# 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)
Expand Down Expand Up @@ -240,13 +253,16 @@ this to make sure unexpected exception types aren't hidden:
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)
Expand All @@ -269,22 +285,28 @@ running from a test you can do something like this:
# 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``
Expand All @@ -301,6 +323,7 @@ It's easy to present extra information in a ``pytest`` run:
# content of conftest.py
def pytest_report_header(config):
return "project deps: mylib-1.1"
Expand All @@ -325,8 +348,9 @@ display more information if applicable:
# 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"::
Expand Down Expand Up @@ -367,12 +391,15 @@ out which tests are the slowest. Let's make an artificial test suite:
# 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)
Expand Down Expand Up @@ -409,17 +436,19 @@ an ``incremental`` marker which is to be used on classes:
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:
Expand All @@ -430,15 +459,19 @@ tests in a class. Here is a test module example:
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
Expand Down Expand Up @@ -489,9 +522,11 @@ Here is an example for making a ``db`` fixture available in a directory:
# content of a/conftest.py
import pytest
class DB(object):
pass
@pytest.fixture(scope="session")
def db():
return DB()
Expand Down Expand Up @@ -600,6 +635,7 @@ case we just write some information out to a ``failures`` file:
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
Expand All @@ -626,6 +662,8 @@ if you then have failing tests:
# content of test_module.py
def test_fail1(tmpdir):
assert 0
def test_fail2():
assert 0
Expand Down Expand Up @@ -678,6 +716,7 @@ here is a little example implemented via a local plugin:
import pytest
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
# execute all other hooks to obtain the report object
Expand All @@ -696,10 +735,10 @@ here is a little example implemented via a local plugin:
# 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:
Expand All @@ -710,16 +749,20 @@ if you then have failing tests:
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
Expand Down Expand Up @@ -787,7 +830,7 @@ test got stuck if necessary:
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
Expand Down Expand Up @@ -841,8 +884,9 @@ like ``pytest-timeout`` they must be imported explicitly and passed on to pytest
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:], plugins=[pytest_timeout]))
else:
# normal application execution: at this point argv can be parsed
Expand Down
Loading

0 comments on commit d609b63

Please sign in to comment.