discover运行原理
assert not _relpath.startswith(’…’), “Path must be within the project”
遇到assert not _relpath.startswith(’…’), "Path must be within the project"如何解决?
在执行不同文件下的测试用例脚本时,提示执行脚本路径必须在此项目中(直白翻译官)。但是我却没有明白,我执行的用例脚本时在当前项目中,为什么会报错?
执行部分代码如下
报错来了
Traceback (most recent call last):
File “E:/apikuangjiatest/dirver/test_runner_V3.py”, line 56, in
discover = unittest.defaultTestLoader.discover(fdir, pattern=fname)
File “C:\Users\xiaopang\AppData\Local\Programs\Python\Python38-32\lib\unittest\loader.py”, line 349, in discover
tests = list(self._find_tests(start_dir, pattern))
File “C:\Users\xiaopang\AppData\Local\Programs\Python\Python38-32\lib\unittest\loader.py”, line 387, in _find_tests
name = self._get_name_from_path(start_dir)
File “C:\Users\xiaopang\AppData\Local\Programs\Python\Python38-32\lib\unittest\loader.py”, line 371, in _get_name_from_path
assert not _relpath.startswith(’…’), “Path must be within the project”
AssertionError: Path must be within the project
报错原因
discover 没有传 top_level_dir时 第一次运行时如果为None 会取当前传入的fdir所在路径为 top_level_dir,而top_level_dir会作为self的参数保存下来,这样第二次运行时 top_level_dir实际取的是上一次的路径,直接影响到了下一次的运行。
举个栗子:如果程序中先运行ind_xxx里面的脚本,再运行mul_xxx里面的脚本,则运行mul_xxx里面的脚本时就会报上面的错。(不知道客观明白了没有?)
解决方法
我运用到的方法是加 top_level_dir参数并且传递脚本对应的运行路径,改变代码如下,其余不变
p1是我当前文件所在路径的上一级目录,相当于我获取的相对路径,当然也可以加绝对路径(比如:E:\a\script),值得注意的是:这个路径是你的测试脚本所在文件夹的上一级目录(栗子:E:\a\script\ind_xxx\testa.py,写路径时需要写为E:\a\script).添加后再次运行就成功了。