pytest start

安装pytest

pip install -U pytest    # -U就是 --upgrade,意思是如果已安装就升级到最新版

A sample

def func(x):  
    return x+1;  
  
def test_answer():  
    assert func(3) == 5

test 结果

============================= test session starts =============================
collecting ... collected 1 item

test_sample.py::test_answer FAILED                                       [100%]
test_sample.py:12 (test_answer)
4 != 5

Expected :5
Actual   :4
<Click to see difference>

def test_answer():
>       assert func(3) == 5
E       assert 4 == 5
E         +4
E         -5

test_sample.py:14: AssertionError


======================== 1 failed, 1 warning in 0.23s =========================

使用assert断言来校验预期值

multiple tests

Pytest 将运行 test _ * 格式的所有文件。工作目录及其子目录中的 py 或 * _ test.py

import pytest  
  
def f():  
    raise SystemExit(1)  
  
def test_mytest():  
    with pytest.raises(SystemExit):  
        f()
PS D:\project\oneday_onecoding\python\pytest_study> pytest -q .\test_sysexit.py 
.                                                                                                                                              [100%]
1 passed, 1 warning in 0.14s

-q 就是quiet模式 打印的内容简洁

test in class

class TestClass:  
    def test_one(self):  
        x = 'this'  
        assert "h" in x  
  
    def test_two(self):  
        x = 'hello'  
        assert hasattr(x,'check')

在类级别添加属性 ,可以在不同的测试中共享 -k (模糊字符串查找执行用例)

class TestClassDemoInstance:  
    value = 0  
  
    def test_one(self):  
        self.value = 1  
        assert self.value == 1  
  
    def test_two(self):  
        assert self.value == 1

-k (模糊字符串查找执行用例) pytest -k TestClassDemoInstance -q

请求临时目录

pytest provides Builtin fixtures/function arguments to request arbitrary resources, like a unique temporary directory
Pytest 提供了 Builtin fixture/function 参数来请求任意资源,比如一个惟一的临时目录:

def test_needsfiles(tmp_path):  
    print(tmp_path)  
    assert 0

tmp_path = WindowsPath('C:/Users/xsc/AppData/Local/Temp/pytest-of-xsc/pytest-0/test_needsfiles0')
pytest --fixtures



C:\Users\xsc>pytest --fixtures
================================================= test session starts =================================================
platform win32 -- Python 3.9.7, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: C:\Users\xsc
plugins: anyio-2.2.0, Faker-14.0.0
collected 0 items / 1 error
cache
    Return a cache object that can persist state between testing sessions.

    cache.get(key, default)
    cache.set(key, value)

    Keys must be ``/`` separated strings, 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 text capturing of writes to ``sys.stdout`` and ``sys.stderr``.

    The captured output is made available via ``capsys.readouterr()`` method
    calls, which return a ``(out, err)`` namedtuple.
    ``out`` and ``err`` will be ``text`` objects.

capsysbinary
    Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.

    The captured output is made available via ``capsysbinary.readouterr()``
    method calls, which return a ``(out, err)`` namedtuple.
    ``out`` and ``err`` will be ``bytes`` objects.

capfd
    Enable text capturing of writes to file descriptors ``1`` and ``2``.

    The captured output is made available via ``capfd.readouterr()`` method
    calls, which return a ``(out, err)`` namedtuple.
    ``out`` and ``err`` will be ``text`` objects.

capfdbinary
    Enable bytes capturing of writes to file descriptors ``1`` and ``2``.

    The captured output is made available via ``capfd.readouterr()`` method
    calls, which return a ``(out, err)`` namedtuple.
    ``out`` and ``err`` will be ``byte`` objects.

doctest_namespace [session scope]
    Fixture that returns a :py:class:`dict` that will be injected into the
    namespace of doctests.

pytestconfig [session scope]
    Session-scoped fixture that returns the :class:`_pytest.config.Config` object.

    Example::

        def test_foo(pytestconfig):
            if pytestconfig.getoption("verbose") > 0:
                ...

record_property
    Add extra properties to 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``. The value is automatically
    XML-encoded.

    Example::

        def test_function(record_property):
            record_property("example_key", 1)

record_xml_attribute
    Add extra xml attributes to the tag for the calling test.

    The fixture is callable with ``name, value``. The value is
    automatically XML-encoded.

record_testsuite_property [session scope]
    Record a new ``<property>`` tag as child of the root ``<testsuite>``.

    This is suitable to writing global information regarding the entire test
    suite, and is compatible with ``xunit2`` JUnit family.

    This is a ``session``-scoped fixture which is called with ``(name, value)``. Example:

    .. code-block:: python

        def test_foo(record_testsuite_property):
            record_testsuite_property("ARCH", "PPC")
            record_testsuite_property("STORAGE_TYPE", "CEPH")

    ``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped.

    .. warning::

        Currently this fixture **does not work** with the
        `pytest-xdist <https://github.com/pytest-dev/pytest-xdist>`__ plugin. See issue
        `#7767 <https://github.com/pytest-dev/pytest/issues/7767>`__ for details.

caplog
    Access and control log capturing.

    Captured logs are available through the following properties/methods::

    * caplog.messages        -> list of format-interpolated log messages
    * 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
    A convenient fixture for monkey-patching.

    The fixture provides these 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, 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 :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 [session scope]
    Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session.

tmp_path_factory [session scope]
    Return a :class:`_pytest.tmpdir.TempPathFactory` 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.

    By default, a new base temporary directory is created each test session,
    and old bases are removed after 3 sessions, to aid in debugging. If
    ``--basetemp`` is used then it is cleared each session. See :ref:`base
    temporary directory`.

    The returned object is a `py.path.local`_ path object.

    .. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html

tmp_path
    Return a temporary directory path object which is unique to each test
    function invocation, created as a sub directory of the base temporary
    directory.

    By default, a new base temporary directory is created each test session,
    and old bases are removed after 3 sessions, to aid in debugging. If
    ``--basetemp`` is used then it is cleared each session. See :ref:`base
    temporary directory`.

    The returned object is a :class:`pathlib.Path` object.

posted @ 2025-02-02 22:38  且任荣枯  阅读(1)  评论(0编辑  收藏  举报