unittest的discover方法

转载:https://www.cnblogs.com/imyalost/p/9048386.html

discover()方法

  discover(start_dir, pattern ='test *.py', top_level_dir = None 

  start_dir:要测试的模块名或测试用例目录;

  pattern='test*.py':表示用例文件名的匹配原则,下面的例子中匹配文件名为以“test”开头的“.py”文件,星号“*”表示任意多个字符;

  top_level_dir=None:测试模块的顶层目录,如果没有顶层目录,默认为None;

  该方法通过从指定的开始目录递归到子目录中查找所有测试模块,并返回包含它们的TestSuite对象,只有与模式匹配测试文件和可导入的模块名称才会被加载。

  所有测试模块必须可以从项目的顶层导入,如果起始目录不是顶层目录,则顶层目录必须单独指定。

  如果一个测试文件的名称符合pattern,将检查该文件是否包含 load_tests() 函数,如果 load_tests() 函数存在,则由该函数负责加载本文件中的测试用例。

  如果不存在,就会执行loadTestsFromModule(),查找该文件中派生自TestCase 的类包含的 test 开头的方法。

 实例:

# coding=utf-8
import unittest
from unittest import defaultTestLoader

# 测试用例存放路径
case_path = './Testcase/case'

# 获取所有测试用例
def get_allcase():
discover = unittest.defaultTestLoader.discover(case_path, pattern="test*.py")
suite = unittest.TestSuite()
suite.addTest(discover)
return suite

if __name__ == '__main__':
# 运行测试用例
runner = unittest.TextTestRunner()
runner.run(get_allcase())

 

posted @ 2019-10-30 16:45  测试爬虫  阅读(356)  评论(0编辑  收藏  举报