pytest中文手册1安装和快速入门

作者: python测试开发 | 来源:发表于2019-06-11 11:09 被阅读37次

安装和快速入门

  • 安装
$ pip install -U pytest
$ pytest --version
This is pytest version 4.3.1, imported from /opt/anaconda3/lib/python3.7/site-packages/pytest.py
setuptools registered plugins:
  pytest-remotedata-0.3.1 at /opt/anaconda3/lib/python3.7/site-packages/pytest_remotedata/plugin.py
  pytest-openfiles-0.3.2 at /opt/anaconda3/lib/python3.7/site-packages/pytest_openfiles/plugin.py
  pytest-metadata-1.8.0 at /opt/anaconda3/lib/python3.7/site-packages/pytest_metadata/plugin.py
  pytest-html-1.20.0 at /opt/anaconda3/lib/python3.7/site-packages/pytest_html/plugin.py
  pytest-doctestplus-0.3.0 at /opt/anaconda3/lib/python3.7/site-packages/pytest_doctestplus/plugin.py
  pytest-arraydiff-0.3 at /opt/anaconda3/lib/python3.7/site-packages/pytest_arraydiff/plugin.py

jython的安装可能要生成脚本,参见:http://pytest.org/latest/getting-started.html

  • 第一个实例:

代码:

# content of test_sample.py
def func(x):
    return x + 1

def test_answer():
    assert func(3) == 5

在当前目录执行:

$ pytest test_sample.py 
====================================================================== test session starts ======================================================================
platform linux -- Python 3.7.3, pytest-4.3.1, py-1.8.0, pluggy-0.9.0
rootdir: /home/andrew/code/pytest_tmp, inifile:
plugins: remotedata-0.3.1, openfiles-0.3.2, metadata-1.8.0, html-1.20.0, doctestplus-0.3.0, arraydiff-0.3
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.13 seconds ==================================================================== 

我们得到了一个故障报告,因为我们调用func(3)没有返回5。pytest的高级內省断言会智能报告assert的中间值,不需要记住那些JUnit传统方法。

  • 执行多个测试

pytest会执行当前目录及其子目录的test_.py 或_test.py。

  • 异常断言

代码:

# content of test_sysexit.py
import pytest
def f():
    raise SystemExit(1)

def test_mytest():
    with pytest.raises(SystemExit):
        f()

执行结果:

$ py.test -q test_sysexit.py
.
1 passed in 0.01 seconds

-q表示静默模式:

-q, --quiet decrease verbosity.
  • 在类中分组用例

代码

# content of test_class.py
class TestClass:
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

执行结果:

$ pytest test_class.py 
====================================================================== test session starts ======================================================================
platform linux -- Python 3.7.3, pytest-4.3.1, py-1.8.0, pluggy-0.9.0
rootdir: /home/andrew/code/pytest_tmp, inifile:
plugins: remotedata-0.3.1, openfiles-0.3.2, metadata-1.8.0, html-1.20.0, doctestplus-0.3.0, arraydiff-0.3
collected 2 items                                                                                                                                               

test_class.py .F                                                                                                                                          [100%]

=========================================================================== FAILURES ============================================================================
______________________________________________________________________ TestClass.test_two _______________________________________________________________________

self = <test_class.TestClass object at 0x7f759fd3b780>

    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.14 seconds ===============================================================

  • 功能测试示例:生成唯一的临时目录

功能测试经常需要创建一些文件,并将其传递给应用程序对象。pytest提供 Builtin fixtures/function 参数允许请求任意资源,例如唯一的临时目录:

# content of test_tmpdir.py
def test_needsfiles(tmpdir):
    print (tmpdir)
    assert 0

执行结果:

$ pytest -q test_tmpdir.py
F                                                                                                                                                         [100%]
=========================================================================== FAILURES ============================================================================
________________________________________________________________________ test_needsfiles ________________________________________________________________________

tmpdir = local('/tmp/pytest-of-andrew/pytest-2/test_needsfiles0')

    def test_needsfiles(tmpdir):
        print (tmpdir)
>       assert 0
E       assert 0

test_tmpdir.py:3: AssertionError
--------------------------------------------------------------------- Captured stdout call ----------------------------------------------------------------------
/tmp/pytest-of-andrew/pytest-2/test_needsfiles0
1 failed in 0.14 seconds

断言的前面的print内容也会打印出来,测试时可以多加print语句,保证异常时输出一些有用的信息。

下面方式可以查看内置功能

$ pytest --fixtures
====================================================================== test session starts ======================================================================
platform linux -- Python 3.7.3, pytest-4.3.1, py-1.8.0, pluggy-0.9.0
rootdir: /home/andrew/code/pytest_tmp, inifile:
plugins: remotedata-0.3.1, openfiles-0.3.2, metadata-1.8.0, html-1.20.0, doctestplus-0.3.0, arraydiff-0.3
collected 5 items                                                                                                                                               
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`` and ``sys.stderr`` and make
    captured output available via ``capsys.readouterr()`` method calls
    which return a ``(out, err)`` namedtuple.  ``out`` and ``err`` will be ``text``
    objects.
capsysbinary
    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
    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
    Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.
pytestconfig
    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_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 properties/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.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, 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
    Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session.
tmp_path_factory
    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.  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.  The returned object is a :class:`pathlib.Path`
    object.
    
    .. note::
    
        in python < 3.6 this is a pathlib2.Path

--------------------------------------------------------- fixtures defined from pytest_metadata.plugin ----------------------------------------------------------
metadata
    Provide test session metadata

================================================================= no tests ran in 0.07 seconds ==================================================================

参考资料

某通信公司的pytest demo

#! /usr/bin/env python
#coding=utf-8

import pytest

@pytest.fixture(scope="module")
def host():
    print "set up"
    import snmp
    host = snmp.Snmp()
    host.snmp_connect(hostname='127.0.0.1', version=2, community='private')
    def close():
        print ("tear down" )
        del host

    return host

@pytest.mark.webtest
@pytest.mark.high
def test_ntp(host):
    host.snmp_connect(hostname='127.0.0.1', version=2, community='private')
    for ip in ('33.33.1.2', '172.22.1.8'):
        host.snmp_set_check('ntpPrimaryServer.0=' + ip)
    for ntpClientEnabled in ('true', 'false'):
        host.snmp_set_check('ntpClientEnabled.0=' + ntpClientEnabled)


@pytest.mark.high
def test_something_quick(host):

    assert 1 == 1
    print "\n test_something_quick"

def test_another():
    pass

#pytest.main("robot_test.py -sv")

参数化:pytest_data_driver.py

import pytest

@pytest.mark.parametrize(("slot_type", "slot_num"), [('ge_10s', '1'), ('xg_1x', '2')])

def test_a(slot_type, slot_num):
    print(slot_type, slot_num)

生成html报告

安装

$ sudo pip install pytest-html

执行:

$ pytest -q test_sysexit.py --html=report.html
.                                                                                                                                                         [100%]
------------------------------------------------- generated html file: /home/andrew/code/pytest_tmp/report.html -------------------------------------------------
1 passed in 0.03 seconds
image.png

相关文章

网友评论

    本文标题:pytest中文手册1安装和快速入门

    本文链接:https://www.haomeiwen.com/subject/fxmffctx.html