use*_*674 19 python testing automated-tests functional-testing python-unittest
我正在扩展python 2.7 unittest
框架来进行一些功能测试.我想做的一件事就是阻止所有测试在测试内部和setUpClass()
方法内部运行.有时如果测试失败,程序就会破坏,不再有任何用处继续测试,所以我想阻止测试运行.
我注意到TestResult有一个shouldStop
属性和一个stop()
方法,但我不确定如何访问测试内部.
有没有人有任何想法?有没有更好的办法?
hpk*_*k42 16
如果您感兴趣,这里有一个简单的例子,您可以自己决定如何使用py.test干净地退出测试套件:
# content of test_module.py
import pytest
counter = 0
def setup_function(func):
global counter
counter += 1
if counter >=3:
pytest.exit("decided to stop the test run")
def test_one():
pass
def test_two():
pass
def test_three():
pass
Run Code Online (Sandbox Code Playgroud)
如果你运行这个你得到:
$ pytest test_module.py
============== test session starts =================
platform linux2 -- Python 2.6.5 -- pytest-1.4.0a1
test path 1: test_module.py
test_module.py ..
!!!! Exit: decided to stop the test run !!!!!!!!!!!!
============= 2 passed in 0.08 seconds =============
Run Code Online (Sandbox Code Playgroud)
您还可以将py.test.exit()
调用放入测试或项目特定的插件中.
旁注:原生py.test
支持py.test --maxfail=NUM
在NUM失败后实施停止.
Sidenote2:py.test
对传统unittest.TestCase
样式运行测试的支持有限.
这是我一段时间后想到的另一个答案:
首先,我添加了一个新的例外:
class StopTests(Exception):
"""
Raise this exception in a test to stop the test run.
"""
pass
Run Code Online (Sandbox Code Playgroud)
然后我assert
在我的孩子测试类中添加了一个新的:
def assertStopTestsIfFalse(self, statement, reason=''):
try:
assert statement
except AssertionError:
result.addFailure(self, sys.exc_info())
Run Code Online (Sandbox Code Playgroud)
最后我覆盖了该run
函数以将其包含在testMethod()
调用的正下方:
except StopTests:
result.addFailure(self, sys.exc_info())
result.stop()
Run Code Online (Sandbox Code Playgroud)
我更喜欢这个,因为现在任何测试都可以停止所有测试,并且没有特定于 cpython 的代码。
归档时间: |
|
查看次数: |
12267 次 |
最近记录: |