Skip to content

Commit e580534

Browse files
authored
doc: Reformat/Modernize some code (#9900)
Found because I was curious what https://pypi.org/project/shed/ does with pytest.
1 parent eb8b3ad commit e580534

16 files changed

+45
-36
lines changed

doc/en/example/attic.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ example: specifying and selecting acceptance tests
2525
self.tmpdir = request.config.mktemp(request.function.__name__, numbered=True)
2626

2727
def run(self, *cmd):
28-
""" called by test code to execute an acceptance test. """
28+
"""called by test code to execute an acceptance test."""
2929
self.tmpdir.chdir()
3030
return subprocess.check_output(cmd).decode()
3131

doc/en/example/markers.rst

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,7 @@ specifies via named environments:
375375
envnames = [mark.args[0] for mark in item.iter_markers(name="env")]
376376
if envnames:
377377
if item.config.getoption("-E") not in envnames:
378-
pytest.skip("test requires env in {!r}".format(envnames))
378+
pytest.skip(f"test requires env in {envnames!r}")
379379
380380
A test file using this local plugin:
381381

@@ -528,7 +528,7 @@ test function. From a conftest file we can read it like this:
528528
529529
def pytest_runtest_setup(item):
530530
for mark in item.iter_markers(name="glob"):
531-
print("glob args={} kwargs={}".format(mark.args, mark.kwargs))
531+
print(f"glob args={mark.args} kwargs={mark.kwargs}")
532532
sys.stdout.flush()
533533
534534
Let's run this without capturing output and see what we get:
@@ -558,6 +558,7 @@ for your particular platform, you could use the following plugin:
558558
# content of conftest.py
559559
#
560560
import sys
561+
561562
import pytest
562563
563564
ALL = set("darwin linux win32".split())
@@ -567,7 +568,7 @@ for your particular platform, you could use the following plugin:
567568
supported_platforms = ALL.intersection(mark.name for mark in item.iter_markers())
568569
plat = sys.platform
569570
if supported_platforms and plat not in supported_platforms:
570-
pytest.skip("cannot run on platform {}".format(plat))
571+
pytest.skip(f"cannot run on platform {plat}")
571572
572573
then tests will be skipped if they were specified for a different platform.
573574
Let's do a little test file to show how this looks like:

doc/en/example/parametrize.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -663,6 +663,7 @@ as a complement to ``raises``. For example:
663663
.. code-block:: python
664664
665665
from contextlib import contextmanager
666+
666667
import pytest
667668
668669

doc/en/example/simple.rst

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ Example:
342342
def checkconfig(x):
343343
__tracebackhide__ = True
344344
if not hasattr(x, "config"):
345-
pytest.fail("not configured: {}".format(x))
345+
pytest.fail(f"not configured: {x}")
346346
347347
348348
def test_something():
@@ -376,6 +376,7 @@ this to make sure unexpected exception types aren't hidden:
376376
.. code-block:: python
377377
378378
import operator
379+
379380
import pytest
380381
381382
@@ -386,7 +387,7 @@ this to make sure unexpected exception types aren't hidden:
386387
def checkconfig(x):
387388
__tracebackhide__ = operator.methodcaller("errisinstance", ConfigException)
388389
if not hasattr(x, "config"):
389-
raise ConfigException("not configured: {}".format(x))
390+
raise ConfigException(f"not configured: {x}")
390391
391392
392393
def test_something():
@@ -565,6 +566,7 @@ an ``incremental`` marker which is to be used on classes:
565566
# content of conftest.py
566567
567568
from typing import Dict, Tuple
569+
568570
import pytest
569571
570572
# store history of failures per test class name and per index in parametrize (if parametrize used)
@@ -608,7 +610,7 @@ an ``incremental`` marker which is to be used on classes:
608610
test_name = _test_failed_incremental[cls_name].get(parametrize_index, None)
609611
# if name found, test has failed for the combination of class name & test name
610612
if test_name is not None:
611-
pytest.xfail("previous test failed ({})".format(test_name))
613+
pytest.xfail(f"previous test failed ({test_name})")
612614
613615
614616
These two hook implementations work together to abort incremental-marked
@@ -802,9 +804,10 @@ case we just write some information out to a ``failures`` file:
802804
803805
# content of conftest.py
804806
805-
import pytest
806807
import os.path
807808
809+
import pytest
810+
808811
809812
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
810813
def pytest_runtest_makereport(item, call):
@@ -1066,6 +1069,7 @@ like ``pytest-timeout`` they must be imported explicitly and passed on to pytest
10661069
10671070
# contents of app_main.py
10681071
import sys
1072+
10691073
import pytest_timeout # Third party plugin
10701074
10711075
if len(sys.argv) > 1 and sys.argv[1] == "--pytest":

doc/en/how-to/assert.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ file which provides an alternative explanation for ``Foo`` objects:
238238
if isinstance(left, Foo) and isinstance(right, Foo) and op == "==":
239239
return [
240240
"Comparing Foo instances:",
241-
" vals: {} != {}".format(left.val, right.val),
241+
f" vals: {left.val} != {right.val}",
242242
]
243243
244244
now, given this test module:

doc/en/how-to/cache.rst

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,6 @@ across pytest invocations:
199199
200200
# content of test_caching.py
201201
import pytest
202-
import time
203202
204203
205204
def expensive_computation():

doc/en/how-to/capture-warnings.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ which works in a similar manner to :ref:`raises <assertraises>`:
253253
.. code-block:: python
254254
255255
import warnings
256+
256257
import pytest
257258
258259

doc/en/how-to/doctest.rst

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,6 @@ which can then be used in your doctests directly:
239239
>>> len(a)
240240
10
241241
"""
242-
pass
243242
244243
Note that like the normal ``conftest.py``, the fixtures are discovered in the directory tree conftest is in.
245244
Meaning that if you put your doctest with your source code, the relevant conftest.py needs to be in the same directory tree.

doc/en/how-to/fixtures.rst

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -398,9 +398,10 @@ access the fixture function:
398398
.. code-block:: python
399399
400400
# content of conftest.py
401-
import pytest
402401
import smtplib
403402
403+
import pytest
404+
404405
405406
@pytest.fixture(scope="module")
406407
def smtp_connection():
@@ -609,10 +610,10 @@ Here's what that might look like:
609610
.. code-block:: python
610611
611612
# content of test_emaillib.py
612-
import pytest
613-
614613
from emaillib import Email, MailAdminClient
615614
615+
import pytest
616+
616617
617618
@pytest.fixture
618619
def mail_admin():
@@ -683,10 +684,10 @@ Here's how the previous example would look using the ``addfinalizer`` method:
683684
.. code-block:: python
684685
685686
# content of test_emaillib.py
686-
import pytest
687-
688687
from emaillib import Email, MailAdminClient
689688
689+
import pytest
690+
690691
691692
@pytest.fixture
692693
def mail_admin():
@@ -752,10 +753,10 @@ above):
752753
.. code-block:: python
753754
754755
# content of test_emaillib.py
755-
import pytest
756-
757756
from emaillib import Email, MailAdminClient
758757
758+
import pytest
759+
759760
760761
@pytest.fixture
761762
def setup():
@@ -1030,16 +1031,17 @@ read an optional server URL from the test module which uses our fixture:
10301031
.. code-block:: python
10311032
10321033
# content of conftest.py
1033-
import pytest
10341034
import smtplib
10351035
1036+
import pytest
1037+
10361038
10371039
@pytest.fixture(scope="module")
10381040
def smtp_connection(request):
10391041
server = getattr(request.module, "smtpserver", "smtp.gmail.com")
10401042
smtp_connection = smtplib.SMTP(server, 587, timeout=5)
10411043
yield smtp_connection
1042-
print("finalizing {} ({})".format(smtp_connection, server))
1044+
print(f"finalizing {smtp_connection} ({server})")
10431045
smtp_connection.close()
10441046
10451047
We use the ``request.module`` attribute to optionally obtain an
@@ -1193,15 +1195,16 @@ through the special :py:class:`request <FixtureRequest>` object:
11931195
.. code-block:: python
11941196
11951197
# content of conftest.py
1196-
import pytest
11971198
import smtplib
11981199
1200+
import pytest
1201+
11991202
12001203
@pytest.fixture(scope="module", params=["smtp.gmail.com", "mail.python.org"])
12011204
def smtp_connection(request):
12021205
smtp_connection = smtplib.SMTP(request.param, 587, timeout=5)
12031206
yield smtp_connection
1204-
print("finalizing {}".format(smtp_connection))
1207+
print(f"finalizing {smtp_connection}")
12051208
smtp_connection.close()
12061209
12071210
The main change is the declaration of ``params`` with
@@ -1503,7 +1506,7 @@ to show the setup/teardown flow:
15031506
15041507
15051508
def test_2(otherarg, modarg):
1506-
print(" RUN test2 with otherarg {} and modarg {}".format(otherarg, modarg))
1509+
print(f" RUN test2 with otherarg {otherarg} and modarg {modarg}")
15071510
15081511
15091512
Let's run the tests in verbose mode and with looking at the print-output:
@@ -1604,6 +1607,7 @@ and declare its use in a test module via a ``usefixtures`` marker:
16041607
16051608
# content of test_setenv.py
16061609
import os
1610+
16071611
import pytest
16081612
16091613

doc/en/how-to/logging.rst

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,6 @@ messages. This is supported by the ``caplog`` fixture:
7373
7474
def test_foo(caplog):
7575
caplog.set_level(logging.INFO)
76-
pass
7776
7877
By default the level is set on the root logger,
7978
however as a convenience it is also possible to set the log level of any
@@ -83,7 +82,6 @@ logger:
8382
8483
def test_foo(caplog):
8584
caplog.set_level(logging.CRITICAL, logger="root.baz")
86-
pass
8785
8886
The log levels set are restored automatically at the end of the test.
8987

@@ -161,9 +159,7 @@ the records for the ``setup`` and ``call`` stages during teardown like so:
161159
x.message for x in caplog.get_records(when) if x.levelno == logging.WARNING
162160
]
163161
if messages:
164-
pytest.fail(
165-
"warning messages encountered during testing: {}".format(messages)
166-
)
162+
pytest.fail(f"warning messages encountered during testing: {messages}")
167163
168164
169165

doc/en/how-to/skipping.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ It is also possible to skip the whole module using
6969
.. code-block:: python
7070
7171
import sys
72+
7273
import pytest
7374
7475
if not sys.platform.startswith("win"):
@@ -409,6 +410,7 @@ test instances when using parametrize:
409410
.. code-block:: python
410411
411412
import sys
413+
412414
import pytest
413415
414416

doc/en/how-to/unittest.rst

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ fixture definition:
115115
# content of test_unittest_db.py
116116
117117
import unittest
118+
118119
import pytest
119120
120121
@@ -194,10 +195,10 @@ creation of a per-test temporary directory:
194195
.. code-block:: python
195196
196197
# content of test_unittest_cleandir.py
197-
import os
198-
import pytest
199198
import unittest
200199
200+
import pytest
201+
201202
202203
class MyTest(unittest.TestCase):
203204
@pytest.fixture(autouse=True)

doc/en/how-to/usage.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,9 +183,10 @@ You can specify additional plugins to ``pytest.main``:
183183
.. code-block:: python
184184
185185
# content of myinvoke.py
186-
import pytest
187186
import sys
188187
188+
import pytest
189+
189190
190191
class MyPlugin:
191192
def pytest_sessionfinish(self):

doc/en/how-to/writing_hook_functions.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ class or module can then be passed to the ``pluginmanager`` using the ``pytest_a
194194
.. code-block:: python
195195
196196
def pytest_addhooks(pluginmanager):
197-
""" This example assumes the hooks are grouped in the 'sample_hook' module. """
197+
"""This example assumes the hooks are grouped in the 'sample_hook' module."""
198198
from my_app.tests import sample_hook
199199
200200
pluginmanager.add_hookspecs(sample_hook)
@@ -253,14 +253,14 @@ and use pytest_addoption as follows:
253253
# default value
254254
@hookspec(firstresult=True)
255255
def pytest_config_file_default_value():
256-
""" Return the default value for the config file command line option. """
256+
"""Return the default value for the config file command line option."""
257257
258258
259259
# contents of myplugin.py
260260
261261
262262
def pytest_addhooks(pluginmanager):
263-
""" This example assumes the hooks are grouped in the 'hooks' module. """
263+
"""This example assumes the hooks are grouped in the 'hooks' module."""
264264
from . import hooks
265265
266266
pluginmanager.add_hookspecs(hooks)

doc/en/how-to/writing_plugins.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ string value of ``Hello World!`` if we do not supply a value or ``Hello
367367
def _hello(name=None):
368368
if not name:
369369
name = request.config.getoption("name")
370-
return "Hello {name}!".format(name=name)
370+
return f"Hello {name}!"
371371
372372
return _hello
373373

doc/en/how-to/xunit_setup.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ which will usually be called once for all the functions:
3232
.. code-block:: python
3333
3434
def setup_module(module):
35-
""" setup any state specific to the execution of the given module."""
35+
"""setup any state specific to the execution of the given module."""
3636
3737
3838
def teardown_module(module):

0 commit comments

Comments
 (0)