Ale*_*lex 20 python unit-testing
根据文档,我可以在调用时设置python unittest的详细级别unittest.main,例如
unittest.main(verbosity=2)
Run Code Online (Sandbox Code Playgroud)
如何在一个unittest.TestCase?中访问此信息?
基于修补或子类化的任何方法的问题unittest.TestProgram在于,您必须在unittest.TestProgram启动之前获取补丁.但是,如果您的测试用例是通过发现来运行的话,这是不可能的:
python -m unittest discover -v
Run Code Online (Sandbox Code Playgroud)
在发现案例中工作的方法是使用inspect模块搜索堆栈,直到unittest.TestProgram找到方法为止:
import inspect
import unittest
def unittest_verbosity():
"""Return the verbosity setting of the currently running unittest
program, or 0 if none is running.
"""
frame = inspect.currentframe()
while frame:
self = frame.f_locals.get('self')
if isinstance(self, unittest.TestProgram):
return self.verbosity
frame = frame.f_back
return 0
Run Code Online (Sandbox Code Playgroud)
实现此目的的一种方法是在文件中子类化unittest.TestCase和。unittest.main在这里,您定义一个可以全局使用或作为类或单例使用的变量(例如globalverb),然后覆盖unittest.main:
def main(*args, **kwargs):
# parse arguments etc to get the verbosity number or whatever
# ...
# set this number to the defined class
globalverb = verbose_number
return unittest.main(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
后来,你继承了unittest.TestCase:
class MyTestCase(unittest.TestCase):
def my_special_function(self):
if globalverb ...
Run Code Online (Sandbox Code Playgroud)
通过这种方法,可以在(派生的)测试用例中使用传递给单元测试的参数的详细信息、详细程度或任何其他数字和信息。
欢迎评论。
| 归档时间: |
|
| 查看次数: |
5508 次 |
| 最近记录: |