@coolfish
2016-11-25T15:04:35.000000Z
字数 3441
阅读 1564
pytest
- 安装
- 简介
- 特性
- 开始
- fixtures
pip install -U pytest
写一个名为test_sample.py的脚本,内容如下:
def func(x):return x + 1def test_answer():assert func(3) == 5
运行一下(注意,如果你不能运行pytest,说明你的pytest版本低了,更新一下就可以了):
$ pytest======= test session starts ========platform linux -- Python 3.5.2, pytest-3.0.4, py-1.4.31, pluggy-0.4.0rootdir: $REGENDOC_TMPDIR, inifile:collected 1 itemstest_sample.py F======= FAILURES ========_______ test_answer ________def test_answer():> assert func(3) == 5E assert 4 == 5E + where 4 = func(3)test_sample.py:5: AssertionError======= 1 failed in 0.12 seconds ========
从结果可以看出来,运行结果日志非常详尽,包含了脚本里错误发生的具体位置。
编写如下内容的test.py
# coding=utf-8class TestClass:@classmethod # 该行不要也可以运行def setup_class(cls):"""整个用例集运行前运行"""print('setup_class')@classmethod # 该行不要也可以运行def teardown_class(cls):"""整个用例集运行完成后运行"""print('teardown_class')def setup(self):"""每个用例执行前运行"""print('setup')def teardown(self):"""每个用例执行后运行"""print('teardown')def test_one(self):print('****test_one')assert Truedef test_two(self):print('****test_two')assert True
运行pytest -s test.py,结果如下:
platform darwin -- Python 2.7.10, pytest-3.0.4, py-1.4.31, pluggy-0.4.0rootdir: /Users/sunhui/Desktop, inifile:plugins: html-1.6collected 2 itemstest.py setup_classsetup****test_one.teardownsetup****test_two.teardownteardown_class
pytest包含许多内置以及第三方的制具(fixtures)方便测试
运行pytest -q --fixtures就可以看到
$ pytest -q --fixturescacheReturn 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 thename of your plugin or application to avoid clashes with other cache users.Values can be any object handled by the json stdlib module.capsysEnable capturing of writes to sys.stdout/sys.stderr and makecaptured output available via ``capsys.readouterr()`` method callswhich return a ``(out, err)`` tuple.capfdEnable capturing of writes to file descriptors 1 and 2 and makecaptured output available via ``capfd.readouterr()`` method callswhich return a ``(out, err)`` tuple.doctest_namespaceInject names into the doctest namespace.pytestconfigthe pytest config object with access to command line opts.record_xml_propertyAdd extra xml properties to the tag for the calling test.The fixture is callable with ``(name, value)``, with value being automaticallyxml-encoded.monkeypatchThe returned ``monkeypatch`` fixture provides thesehelper 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, value, raising=True)monkeypatch.syspath_prepend(path)monkeypatch.chdir(path)All modifications will be undone after the requestingtest function or fixture has finished. The ``raising``parameter determines if a KeyError or AttributeErrorwill be raised if the set/deletion operation has no target.recwarnReturn a WarningsRecorder instance that provides these methods:* ``pop(category=None)``: return last warning matching the category.* ``clear()``: clear list of warningsSee http://docs.python.org/library/warnings.html for informationon warning categories.tmpdir_factoryReturn a TempdirFactory instance for the test session.tmpdirReturn a temporary directory path objectwhich is unique to each test function invocation,created as a sub directory of the base temporarydirectory. The returned object is a `py.path.local`_path object.no tests ran in 0.12 seconds