我分心了,最终用python编写了一个测试框架。我正在为此提出一个特殊的问题。
在断言期间,我想引发异常,以将问题冒泡到run_test()方法,而无需用户对框架有任何了解。问题是,当我这样做时,try / catch块似乎没有兑现。
这是我刚起步的框架的简化版本:
# test_framework.py
import inspect
import module_containing_tests
class AssertionException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
def run_test(test_name, test_method):
try:
print(">", test_name)
test_method()
print("Passed")
except AssertionException as error:
print("Failed")
print(str(error))
def assert_true(conditional):
if not conditional:
raise AssertionException("Expected True. Was False")
def test(func):
func.is_test = True
return func
members = inspect.getmembers(module_containing_tests)
for member in members:
if "is_test" in dir(member[1]) and not member[0] == "module_containing_tests":
run_test(member[0], member[1])
包含测试的模块如下所示:
# module_containing_tests.py
from test_framework import *
@test
def passing_test():
assert_true(1 + 2 == 3)
@test
def failing_test():
assert_true(1 + 2 == 5)
输出中包含所有异常堆栈的跟踪信息,并且还会中止执行
λ python test_framework.py
> failing_test
Traceback (most recent call last):
File "test_framework.py", line 29, in <module>
run_test(member[0], member[1])
File "test_framework.py", line 13, in run_test
test_method()
File "C:\Git\simpy-test\module_containing_tests.py", line 9, in failing_test
assert_true(1 + 2 == 5)
File "C:\Git\simpy-test\test_framework.py", line 20, in assert_true
raise AssertionException("Expected True. Was False")
test_framework.AssertionException: Expected True. Was False
我想要的是这样的:
λ python test_framework.py
> failing_test
Expected True. Was False
Failed
> passing_test
Passed
我认为这个问题是部分在两个文件中,可能乱用的方法的可见性(如莫名其妙地解释之间的循环引用在这里),并可能部分是,在进场。如果考虑其他的测试框架有多少工作,通常会包含3个元素:要测试的单元,测试框架和测试运行器。
因此,如果我们尝试按照该逻辑拆分所有文档,那么您最终将拥有:
test_framework.py
# test_framework.py
class AssertionException(Exception):
pass
def test(f):
f.is_test = True
return f
def assert_true(conditional):
if not conditional:
raise AssertionException("Expected True. Was False")
test_runner.py
# test_runner.py
import inspect
import unit_test
from test_framework import AssertionException
def run_test(test_name, test_method):
try:
print(">", test_name)
test_method()
print("Passed")
except AssertionException as error:
print("Failed with AssertionException: " + str(error))
except Exception as error:
print("Failed with Exception: " + str(error))
if __name__ == "__main__":
members = inspect.getmembers(unit_test)
for member in members:
if "is_test" in dir(member[1]):
run_test(member[0], member[1])
unit_test.py
# unit_test.py
from test_framework import *
@test
def a_passing_test():
assert_true(1 + 2 == 3)
@test
def z_failing_test():
assert_true(1 + 2 == 5)
通过这种设置,可以消除循环依赖性,并遵守所有可见性上下文,并且输出/行为是预期的。
希望对您有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句