tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

builtin.rst (10465B)


      1 :orphan:
      2 
      3 .. _`pytest helpers`:
      4 
      5 Pytest API and builtin fixtures
      6 ================================================
      7 
      8 
      9 Most of the information of this page has been moved over to :ref:`api-reference`.
     10 
     11 For information on plugin hooks and objects, see :ref:`plugins`.
     12 
     13 For information on the ``pytest.mark`` mechanism, see :ref:`mark`.
     14 
     15 For information about fixtures, see :ref:`fixtures`. To see a complete list of available fixtures (add ``-v`` to also see fixtures with leading ``_``), type :
     16 
     17 .. code-block:: pytest
     18 
     19    $ pytest  --fixtures -v
     20    =========================== test session starts ============================
     21    platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
     22    cachedir: .pytest_cache
     23    rootdir: /home/sweet/project
     24    collected 0 items
     25    cache -- .../_pytest/cacheprovider.py:549
     26        Return a cache object that can persist state between testing sessions.
     27 
     28        cache.get(key, default)
     29        cache.set(key, value)
     30 
     31        Keys must be ``/`` separated strings, where the first part is usually the
     32        name of your plugin or application to avoid clashes with other cache users.
     33 
     34        Values can be any object handled by the json stdlib module.
     35 
     36    capsysbinary -- .../_pytest/capture.py:1003
     37        Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.
     38 
     39        The captured output is made available via ``capsysbinary.readouterr()``
     40        method calls, which return a ``(out, err)`` namedtuple.
     41        ``out`` and ``err`` will be ``bytes`` objects.
     42 
     43        Returns an instance of :class:`CaptureFixture[bytes] <pytest.CaptureFixture>`.
     44 
     45        Example:
     46        .. code-block:: python
     47 
     48            def test_output(capsysbinary):
     49                print("hello")
     50                captured = capsysbinary.readouterr()
     51                assert captured.out == b"hello\n"
     52 
     53    capfd -- .../_pytest/capture.py:1030
     54        Enable text capturing of writes to file descriptors ``1`` and ``2``.
     55 
     56        The captured output is made available via ``capfd.readouterr()`` method
     57        calls, which return a ``(out, err)`` namedtuple.
     58        ``out`` and ``err`` will be ``text`` objects.
     59 
     60        Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.
     61 
     62        Example:
     63        .. code-block:: python
     64 
     65            def test_system_echo(capfd):
     66                os.system('echo "hello"')
     67                captured = capfd.readouterr()
     68                assert captured.out == "hello\n"
     69 
     70    capfdbinary -- .../_pytest/capture.py:1057
     71        Enable bytes capturing of writes to file descriptors ``1`` and ``2``.
     72 
     73        The captured output is made available via ``capfd.readouterr()`` method
     74        calls, which return a ``(out, err)`` namedtuple.
     75        ``out`` and ``err`` will be ``byte`` objects.
     76 
     77        Returns an instance of :class:`CaptureFixture[bytes] <pytest.CaptureFixture>`.
     78 
     79        Example:
     80        .. code-block:: python
     81 
     82            def test_system_echo(capfdbinary):
     83                os.system('echo "hello"')
     84                captured = capfdbinary.readouterr()
     85                assert captured.out == b"hello\n"
     86 
     87    capsys -- .../_pytest/capture.py:976
     88        Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``.
     89 
     90        The captured output is made available via ``capsys.readouterr()`` method
     91        calls, which return a ``(out, err)`` namedtuple.
     92        ``out`` and ``err`` will be ``text`` objects.
     93 
     94        Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.
     95 
     96        Example:
     97        .. code-block:: python
     98 
     99            def test_output(capsys):
    100                print("hello")
    101                captured = capsys.readouterr()
    102                assert captured.out == "hello\n"
    103 
    104    doctest_namespace [session scope] -- .../_pytest/doctest.py:738
    105        Fixture that returns a :py:class:`dict` that will be injected into the
    106        namespace of doctests.
    107 
    108        Usually this fixture is used in conjunction with another ``autouse`` fixture:
    109 
    110        .. code-block:: python
    111 
    112            @pytest.fixture(autouse=True)
    113            def add_np(doctest_namespace):
    114                doctest_namespace["np"] = numpy
    115 
    116        For more details: :ref:`doctest_namespace`.
    117 
    118    pytestconfig [session scope] -- .../_pytest/fixtures.py:1335
    119        Session-scoped fixture that returns the session's :class:`pytest.Config`
    120        object.
    121 
    122        Example::
    123 
    124            def test_foo(pytestconfig):
    125                if pytestconfig.getoption("verbose") > 0:
    126                    ...
    127 
    128    record_property -- .../_pytest/junitxml.py:284
    129        Add extra properties to the calling test.
    130 
    131        User properties become part of the test report and are available to the
    132        configured reporters, like JUnit XML.
    133 
    134        The fixture is callable with ``name, value``. The value is automatically
    135        XML-encoded.
    136 
    137        Example::
    138 
    139            def test_function(record_property):
    140                record_property("example_key", 1)
    141 
    142    record_xml_attribute -- .../_pytest/junitxml.py:307
    143        Add extra xml attributes to the tag for the calling test.
    144 
    145        The fixture is callable with ``name, value``. The value is
    146        automatically XML-encoded.
    147 
    148    record_testsuite_property [session scope] -- .../_pytest/junitxml.py:345
    149        Record a new ``<property>`` tag as child of the root ``<testsuite>``.
    150 
    151        This is suitable to writing global information regarding the entire test
    152        suite, and is compatible with ``xunit2`` JUnit family.
    153 
    154        This is a ``session``-scoped fixture which is called with ``(name, value)``. Example:
    155 
    156        .. code-block:: python
    157 
    158            def test_foo(record_testsuite_property):
    159                record_testsuite_property("ARCH", "PPC")
    160                record_testsuite_property("STORAGE_TYPE", "CEPH")
    161 
    162        :param name:
    163            The property name.
    164        :param value:
    165            The property value. Will be converted to a string.
    166 
    167        .. warning::
    168 
    169            Currently this fixture **does not work** with the
    170            `pytest-xdist <https://github.com/pytest-dev/pytest-xdist>`__ plugin. See
    171            :issue:`7767` for details.
    172 
    173    tmpdir_factory [session scope] -- .../_pytest/legacypath.py:303
    174        Return a :class:`pytest.TempdirFactory` instance for the test session.
    175 
    176    tmpdir -- .../_pytest/legacypath.py:310
    177        Return a temporary directory path object which is unique to each test
    178        function invocation, created as a sub directory of the base temporary
    179        directory.
    180 
    181        By default, a new base temporary directory is created each test session,
    182        and old bases are removed after 3 sessions, to aid in debugging. If
    183        ``--basetemp`` is used then it is cleared each session. See
    184        :ref:`temporary directory location and retention`.
    185 
    186        The returned object is a `legacy_path`_ object.
    187 
    188        .. note::
    189            These days, it is preferred to use ``tmp_path``.
    190 
    191            :ref:`About the tmpdir and tmpdir_factory fixtures<tmpdir and tmpdir_factory>`.
    192 
    193        .. _legacy_path: https://py.readthedocs.io/en/latest/path.html
    194 
    195    caplog -- .../_pytest/logging.py:602
    196        Access and control log capturing.
    197 
    198        Captured logs are available through the following properties/methods::
    199 
    200        * caplog.messages        -> list of format-interpolated log messages
    201        * caplog.text            -> string containing formatted log output
    202        * caplog.records         -> list of logging.LogRecord instances
    203        * caplog.record_tuples   -> list of (logger_name, level, message) tuples
    204        * caplog.clear()         -> clear captured records and formatted log output string
    205 
    206    monkeypatch -- .../_pytest/monkeypatch.py:33
    207        A convenient fixture for monkey-patching.
    208 
    209        The fixture provides these methods to modify objects, dictionaries, or
    210        :data:`os.environ`:
    211 
    212        * :meth:`monkeypatch.setattr(obj, name, value, raising=True) <pytest.MonkeyPatch.setattr>`
    213        * :meth:`monkeypatch.delattr(obj, name, raising=True) <pytest.MonkeyPatch.delattr>`
    214        * :meth:`monkeypatch.setitem(mapping, name, value) <pytest.MonkeyPatch.setitem>`
    215        * :meth:`monkeypatch.delitem(obj, name, raising=True) <pytest.MonkeyPatch.delitem>`
    216        * :meth:`monkeypatch.setenv(name, value, prepend=None) <pytest.MonkeyPatch.setenv>`
    217        * :meth:`monkeypatch.delenv(name, raising=True) <pytest.MonkeyPatch.delenv>`
    218        * :meth:`monkeypatch.syspath_prepend(path) <pytest.MonkeyPatch.syspath_prepend>`
    219        * :meth:`monkeypatch.chdir(path) <pytest.MonkeyPatch.chdir>`
    220        * :meth:`monkeypatch.context() <pytest.MonkeyPatch.context>`
    221 
    222        All modifications will be undone after the requesting test function or
    223        fixture has finished. The ``raising`` parameter determines if a :class:`KeyError`
    224        or :class:`AttributeError` will be raised if the set/deletion operation does not have the
    225        specified target.
    226 
    227        To undo modifications done by the fixture in a contained scope,
    228        use :meth:`context() <pytest.MonkeyPatch.context>`.
    229 
    230    recwarn -- .../_pytest/recwarn.py:32
    231        Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.
    232 
    233        See https://docs.pytest.org/en/latest/how-to/capture-warnings.html for information
    234        on warning categories.
    235 
    236    tmp_path_factory [session scope] -- .../_pytest/tmpdir.py:242
    237        Return a :class:`pytest.TempPathFactory` instance for the test session.
    238 
    239    tmp_path -- .../_pytest/tmpdir.py:257
    240        Return a temporary directory path object which is unique to each test
    241        function invocation, created as a sub directory of the base temporary
    242        directory.
    243 
    244        By default, a new base temporary directory is created each test session,
    245        and old bases are removed after 3 sessions, to aid in debugging.
    246        This behavior can be configured with :confval:`tmp_path_retention_count` and
    247        :confval:`tmp_path_retention_policy`.
    248        If ``--basetemp`` is used then it is cleared each session. See
    249        :ref:`temporary directory location and retention`.
    250 
    251        The returned object is a :class:`pathlib.Path` object.
    252 
    253 
    254    ========================== no tests ran in 0.12s ===========================
    255 
    256 You can also interactively ask for help, e.g. by typing on the Python interactive prompt something like:
    257 
    258 .. code-block:: python
    259 
    260    import pytest
    261 
    262    help(pytest)