[关闭]
@coolfish 2016-11-25T15:04:35.000000Z 字数 3441 阅读 1492

pytest

pytest


  • 安装
  • 简介
  • 特性
  • 开始
  • fixtures

1 安装

  1. pip install -U pytest

2 简介

写一个名为test_sample.py的脚本,内容如下:

  1. def func(x):
  2. return x + 1
  3. def test_answer():
  4. assert func(3) == 5

运行一下(注意,如果你不能运行pytest,说明你的pytest版本低了,更新一下就可以了):

  1. $ pytest
  2. ======= test session starts ========
  3. platform linux -- Python 3.5.2, pytest-3.0.4, py-1.4.31, pluggy-0.4.0
  4. rootdir: $REGENDOC_TMPDIR, inifile:
  5. collected 1 items
  6. test_sample.py F
  7. ======= FAILURES ========
  8. _______ test_answer ________
  9. def test_answer():
  10. > assert func(3) == 5
  11. E assert 4 == 5
  12. E + where 4 = func(3)
  13. test_sample.py:5: AssertionError
  14. ======= 1 failed in 0.12 seconds ========

从结果可以看出来,运行结果日志非常详尽,包含了脚本里错误发生的具体位置。


3 特性


4 开始

4.1 用例搜索规则

4.2 在一个类里组织多个用例

编写如下内容的test.py

  1. # coding=utf-8
  2. class TestClass:
  3. @classmethod # 该行不要也可以运行
  4. def setup_class(cls):
  5. """
  6. 整个用例集运行前运行
  7. """
  8. print('setup_class')
  9. @classmethod # 该行不要也可以运行
  10. def teardown_class(cls):
  11. """
  12. 整个用例集运行完成后运行
  13. """
  14. print('teardown_class')
  15. def setup(self):
  16. """
  17. 每个用例执行前运行
  18. """
  19. print('setup')
  20. def teardown(self):
  21. """
  22. 每个用例执行后运行
  23. """
  24. print('teardown')
  25. def test_one(self):
  26. print('****test_one')
  27. assert True
  28. def test_two(self):
  29. print('****test_two')
  30. assert True

运行pytest -s test.py,结果如下:

  1. platform darwin -- Python 2.7.10, pytest-3.0.4, py-1.4.31, pluggy-0.4.0
  2. rootdir: /Users/sunhui/Desktop, inifile:
  3. plugins: html-1.6
  4. collected 2 items
  5. test.py setup_class
  6. setup
  7. ****test_one
  8. .teardown
  9. setup
  10. ****test_two
  11. .teardown
  12. teardown_class

5 fixtures

pytest包含许多内置以及第三方的制具(fixtures)方便测试

5.1 内置fixtures

运行pytest -q --fixtures就可以看到

  1. $ pytest -q --fixtures
  2. cache
  3. Return a cache object that can persist state between testing sessions.
  4. cache.get(key, default)
  5. cache.set(key, value)
  6. Keys must be a ``/`` separated value, where the first part is usually the
  7. name of your plugin or application to avoid clashes with other cache users.
  8. Values can be any object handled by the json stdlib module.
  9. capsys
  10. Enable capturing of writes to sys.stdout/sys.stderr and make
  11. captured output available via ``capsys.readouterr()`` method calls
  12. which return a ``(out, err)`` tuple.
  13. capfd
  14. Enable capturing of writes to file descriptors 1 and 2 and make
  15. captured output available via ``capfd.readouterr()`` method calls
  16. which return a ``(out, err)`` tuple.
  17. doctest_namespace
  18. Inject names into the doctest namespace.
  19. pytestconfig
  20. the pytest config object with access to command line opts.
  21. record_xml_property
  22. Add extra xml properties to the tag for the calling test.
  23. The fixture is callable with ``(name, value)``, with value being automatically
  24. xml-encoded.
  25. monkeypatch
  26. The returned ``monkeypatch`` fixture provides these
  27. helper methods to modify objects, dictionaries or os.environ::
  28. monkeypatch.setattr(obj, name, value, raising=True)
  29. monkeypatch.delattr(obj, name, raising=True)
  30. monkeypatch.setitem(mapping, name, value)
  31. monkeypatch.delitem(obj, name, raising=True)
  32. monkeypatch.setenv(name, value, prepend=False)
  33. monkeypatch.delenv(name, value, raising=True)
  34. monkeypatch.syspath_prepend(path)
  35. monkeypatch.chdir(path)
  36. All modifications will be undone after the requesting
  37. test function or fixture has finished. The ``raising``
  38. parameter determines if a KeyError or AttributeError
  39. will be raised if the set/deletion operation has no target.
  40. recwarn
  41. Return a WarningsRecorder instance that provides these methods:
  42. * ``pop(category=None)``: return last warning matching the category.
  43. * ``clear()``: clear list of warnings
  44. See http://docs.python.org/library/warnings.html for information
  45. on warning categories.
  46. tmpdir_factory
  47. Return a TempdirFactory instance for the test session.
  48. tmpdir
  49. Return a temporary directory path object
  50. which is unique to each test function invocation,
  51. created as a sub directory of the base temporary
  52. directory. The returned object is a `py.path.local`_
  53. path object.
  54. no tests ran in 0.12 seconds

5.1.1 cache

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注