def discover(self, start_dir, pattern='test*.py', top_level_dir=None):
set_implicit_top = False
if top_level_dir is None and self._top_level_dir is not None:
# make top_level_dir optional if called from load_tests in a package
top_level_dir = self._top_level_dir
elif top_level_dir is None:
set_implicit_top = True
top_level_dir = start_dir
top_level_dir = os.path.abspath(top_level_dir)
if not top_level_dir in sys.path:
# all test modules must be importable from the top level directory
# should we *unconditionally* put the start directory in first
# in sys.path to minimise likelihood of conflicts between installed
# modules and development versions?
sys.path.insert(0, top_level_dir)
self._top_level_dir = top_level_dir
is_not_importable = False
if os.path.isdir(os.path.abspath(start_dir)):
start_dir = os.path.abspath(start_dir)
if start_dir != top_level_dir:
is_not_importable = not os.path.isfile(os.path.join(start_dir, '__init__.py'))
else:
# support for discovery from dotted module names
try:
__import__(start_dir)
except ImportError:
is_not_importable = True
else:
the_module = sys.modules[start_dir]
top_part = start_dir.split('.')[0]
start_dir = os.path.abspath(os.path.dirname((the_module.__file__)))
if set_implicit_top:
self._top_level_dir = self._get_directory_containing_module(top_part)
sys.path.remove(top_level_dir)
if is_not_importable:
raise ImportError('Start directory is not importable: %r' % start_dir)
tests = list(self._find_tests(start_dir, pattern))
return self.suiteClass(tests)
分析1:
set_implicit_top = False
if top_level_dir is None and self._top_level_dir is not None:
# make top_level_dir optional if called from load_tests in a package
top_level_dir = self._top_level_dir
elif top_level_dir is None:
set_implicit_top = True
top_level_dir = start_dir
#上面是提出顶层目录
top_level_dir = os.path.abspath(top_level_dir) #顶层目录的绝对路径
if not top_level_dir in sys.path: #判断顶层目录有没有在sys.path中,如果没有,则添加到sys.path中
sys.path.insert(0, top_level_dir)
self._top_level_dir = top_level_dir
这段代码:提取出顶层目录top_level_dir,然后将顶层目录加到sys.path中。
分析2:
is_not_importable = False
if os.path.isdir(os.path.abspath(start_dir)):
start_dir = os.path.abspath(start_dir)
if start_dir != top_level_dir:
is_not_importable = not os.path.isfile(os.path.join(start_dir, '__init__.py'))
本段代码:判断传入的参数start_dir是不是个目录,如果是,将start_dir的绝对路径与top_level_dir的绝对路径进行比较,如果start_dir 绝对路径不等于 top_level_dir绝对路径,那么判断该start_dir目录是否可作为一个包。
如何判断start_dir是不是一个包,通过判断start_dir目录下有没有__init__.py文件,如果start_dir目录下有__init__.py文件,则start_dir就是一个包。如果没有_init__.py文件,那么会报有报错提示
if is_not_importable:
raise ImportError('Start directory is not importable: %r' % start_dir)
分析3:
tests = list(self._find_tests(start_dir, pattern))
return self.suiteClass(tests)
通过调用_find_tests()方法,通过start_dir和pattern测试用例文件,搜索出所需要的测试用例列表,转换成TestSuite类型后返回。
_find_tests() 的源码有待分析,后续更新…