1 pip install -U pytest # or 2 easy_install -U pytest
检查版本:
1 # py.test --version 2 This is pytest version 2.5.2, imported from /usr/lib/python2.7/site-packages/pytest.pyc
代码:
1 # content of test_sample.py
2 def func(x): 3 return x + 1
4 def test_answer(): 5 assert func(3) == 5
执行结果:
1 # py.test
2 =========================================================================================================== test session starts ===========================================================================================================
3 platform linux2 -- Python 2.7.3 -- py-1.4.20 -- pytest-2.5.2
4 collected 1 items 5
6 test_sample.py F
7
8 ================================================================================================================ FAILURES =================================================================================================================
9 _______________________________________________________________________________________________________________ test_answer _______________________________________________________________________________________________________________ 10
11 def test_answer(): 12 > assert func(3) == 5
13 E assert 4 == 5
14 E + where 4 = func(3) 15
16 test_sample.py:8: AssertionError 17 ======================================================================================================== 1 failed in 0.34 seconds =========================================================================================================
pytest通过标准测试发现规则发现test_answer函数,通常是查找 test_前缀。我们得到了一个故障报告,因为我们调用func(3)没有返回5。pytest的高级內省断言会智能报告assert的中间值,不需要记住那些JUnit传统方法。
代码:
1 import pytest 2 def f(): 3 raise SystemExit(1) 4 def test_mytest(): 5 with pytest.raises(SystemExit): 6 f()
执行结果:
1 $ py.test -q test_sysexit.py 2 . 3 1 passed in 0.01 seconds
-q表示静默模式:
1 -q, --quiet decrease verbosity.
代码
1 # content of test_class.py
2 class TestClass: 3 def test_one(self): 4 x = "this"
5 assert 'h' in x 6
7 def test_two(self): 8 x = "hello"
9 assert hasattr(x, 'check')
执行结果:
1 # py.test test_class.py
2 =========================================================================================================== test session starts ===========================================================================================================
3 platform linux2 -- Python 2.7.3 -- py-1.4.20 -- pytest-2.5.2
4 collected 2 items 5
6 test_class.py .F
7
8 ================================================================================================================ FAILURES =================================================================================================================
9 ___________________________________________________________________________________________________________ TestClass.test_two ____________________________________________________________________________________________________________ 10
11 self =
12
13 def test_two(self): 14 x = "hello"
15 > assert hasattr(x, 'check') 16 E assert hasattr('hello', 'check') 17
18 test_class.py:12: AssertionError 19 =================================================================================================== 1 failed, 1 passed in 0.01 seconds ====================================================================================================
功能测试经常需要创建一些文件,并将其传递给应用程序对象。pytest提供 Builtin fixtures/function 参数允许请求任意资源,例如唯一的临时目录:
1 def test_needsfiles(tmpdir): 2 print tmpdir 3 assert 0
执行结果:
1 ]# py.test -q test_tmpdir.py
2 FF
3 ================================================================================================================ FAILURES =================================================================================================================
4 _____________________________________________________________________________________________________________ test_needsfiles _____________________________________________________________________________________________________________
5
6 tmpdir = local('/tmp/pytest-0/test_needsfiles0')
7
8 def test_needsfiles(tmpdir):
9 print tmpdir 10 > assert 0
11 E assert 0
12
13 test_tmpdir.py:7: AssertionError 14 ------------------------------------------------------------------------------------------------------------- Captured stdout -------------------------------------------------------------------------------------------------------------
15 /tmp/pytest-0/test_needsfiles0 16 1 failed in 0.07 seconds
断言的前面的print内容也会打印出来,测试时可以多加print语句,保证异常时输出一些有用的信息。
下面方式可以查看内置的
1 # py.test --fixtures
2
3 =========================================================================================================== test session starts ===========================================================================================================
4 platform linux2 -- Python 2.7.3 -- py-1.4.20 -- pytest-2.5.2
5 collected 5 items 6 capsys
7 enables capturing of writes to sys.stdout/sys.stderr and makes
8 captured output available viacapsys.readouterr()
method calls
9 which return a(out, err)
tuple. 10
11 capfd 12 enables capturing of writes to file descriptors 1 and 2 and makes 13 captured output available viacapsys.readouterr()
method calls 14 which return a(out, err)
tuple. 15
16 monkeypatch 17 The returnedmonkeypatch
funcarg provides these 18 helper methods to modify objects, dictionaries or os.environ:: 19
20 monkeypatch.setattr(obj, name, value, raising=True) 21 monkeypatch.delattr(obj, name, raising=True) 22 monkeypatch.setitem(mapping, name, value) 23 monkeypatch.delitem(obj, name, raising=True) 24 monkeypatch.setenv(name, value, prepend=False) 25 monkeypatch.delenv(name, value, raising=True) 26 monkeypatch.syspath_prepend(path) 27 monkeypatch.chdir(path) 28
29 All modifications will be undone after the requesting 30 test function has finished. Theraising
31 parameter determines if a KeyError or AttributeError 32 will be raised if the set/deletion operation has no target. 33
34 pytestconfig 35 the pytest config object with access to command line opts. 36 recwarn 37 Return a WarningsRecorder instance that provides these methods: 38
39 *pop(category=None)
: return last warning matching the category. 40 *clear()
: clear list of warnings 41
42 See http://docs.python.org/library/warnings.html for information
43 on warning categories. 44
45 tmpdir 46 return a temporary directory path object
47 which is unique to each test function invocation, 48 created as a sub directory of the base temporary 49 directory. The returned object is apy.path.local
_ 50 path object. 51
52
53 ============================================================================================================ in 0.02 seconds =============================================================================================================
Python带有一个内置的Python调试器称为PDB。pytest可以在命令行选项指定调用:
py.test --pdb
这将每次失败时调用Python调试器。
py.test -x --pdb # 失败时调用pdb,然后退出测试。
py.test --pdb - maxfail=3# 前3次失败调用pdb。
1 import pytest 2 def test_function(): 3 ... 4 pytest.set_trace() # invoke PDB debugger and tracing
以前的版本中只有通过py.test-s禁用命令行捕捉才可以进入pdb调试。
py.test --durations=10
创建Hudson或其他持续集成服务器的结果文件:
py.test --junitxml=path
要创建纯文本的机器可读的结果文件,用于PyPy-testweb展示等。
py.test --resultlog=path
bpaste可以为你的文本生成url连接,下面为创建每个测试失败创建一个url:
py.test --pastebin=failed
py.test --pastebin=all
py.test --pastebin=failed -x
目前只支持:py.test --pastebin=failed
禁用插件
py.test -p no:doctest
在python代码中调用pytest
1 pytest.main([’-x’, ’mytestdir’]) 2 pytest.main("-x mytestdir") 3 # 指定插件
4 # content of myinvoke.py
5 import pytest 6 class MyPlugin: 7 def pytest_sessionfinish(self): 8 print("***test run reporting finishing") 9 pytest.main("-qq", plugins=[MyPlugin()])
执行结果:
1 $ python myinvoke.py 2 ***
3 test run reporting finishing
1 #virtualenv .
2 New python executable in ./bin/python
3 Installing setuptools, pip...done.
4 root@AutoTest:[/data/code/python/pytest]#source bin/activate
5 (pytest)root@AutoTest:[/data/code/python/pytest]#pip install pytest 6 Downloading/unpacking pytest
7 Downloading pytest-2.5.2.tar.gz (608kB): 608kB downloaded
8 Running setup.py (path:/data/code/python/pytest/build/pytest/setup.py) egg_info for package pytest 9
10 Downloading/unpacking py>=1.4.20 (from pytest) 11 Downloading py-1.4.22.tar.gz (189kB): 189kB downloaded 12 Running setup.py (path:/data/code/python/pytest/build/py/setup.py) egg_info for package py 13
14 Installing collected packages: pytest, py 15 Running setup.py install for pytest 16
17 Installing py.test-2.7 script to /data/code/python/pytest/bin 18 Installing py.test script to /data/code/python/pytest/bin 19 Running setup.py install for py 20
21 Successfully installed pytest py 22 Cleaning up...
测试布局的方法有2种。一为放置在应用代码之外,适用于有很多功能测试等情况。
setup.py # your distutils/setuptools Python package metadata
mypkg/ init.py
appmodule.py
tests/ test_app.py
...
二为嵌入测试目录到应用,当(单元)测试和应用之间的有直接关系,并想一起发布时有用:
setup.py # your distutils/setuptools Python package metadata
mypkg/ init.py
appmodule.py
...
test/ test_app.py
...