加载中...

菜谱 8:支持简单命令行


本任务最初的目的只是为了在测试过程中使用简单的命令行运行不同的函数,类似运行 “python test_test.py” 运行整个测试,运行 “python test_test.py debug” 来运行测试但是不收集运行结果,请看如下的代码:

  1. import unittest
  2. import sys
  3. class Tests(unittest.TestCase):
  4. def testAddOnePlusOne(self):
  5. assert 1 == 2
  6. def main():
  7. unittest.TextTestRunner().run(test_suite())
  8. def test_suite():
  9. return unittest.makeSuite(Tests, 'test')
  10. def debug():
  11. test_suite().debug()
  12. if __name__ == '__main__':
  13. if len(sys.argv) > 1:
  14. globals()[sys.argv[1]]()
  15. else:
  16. main()

这里如果在命令行中直接运行 “python cookbook_8.py” 就会执行 “main()”;如果在命令行中运行 “python cookbook_8.py debug” 会执行 “debug()”。

“globals()” 返回的是当前全局变量的引用。如果有其它的需求,可以充分利用本任务来延伸!


还没有评论.