当前位置:网站首页>UnitTest中的Path must be within the project 问题

UnitTest中的Path must be within the project 问题

2022-08-10 19:01:00 觅梦_feng

目前在代码中有如下结构:

        discover = unittest.defaultTestLoader.discover(test_dir, pattern='Case*.py')
        if runType.find("main") >= 0 :
            #此处说明是通过执行器启动的单个用例测试,需生成单个用例的测试套件
            dirList = runType.split("\\")
            index = len(dirList)
            testClassName = dirList[index -1 ]
            #由于可能传入不同地址的测试用例 这里需要动态生成测试用例目录地址
            start_index = dirList.index("main") + 1
            test_dir = './'
            for i in range(start_index, index - 1) :
                test_dir += dirList[i] + '/'
            print test_dir    
            discover = unittest.defaultTestLoader.discover(test_dir, pattern=testClassName) 

也就是说 代码开始时需要生成一个 discover 给UnitTest进行run,之后由于不同的测试目的需要运行不同文件夹下的用例 这样就需要再更新一个 discover

运行时实际会报错Path must be within the project

根据代码字面意思 _relpath.startswith(‘…’) 就会报错,但是同样的两次调用为啥会有这样的问题呢?

查看了下discover的代码逻辑发现

unitTest中的 discover 第三个参数 top_level_dir 第一次运行时如果为None 会取当前传入的start_dir所在路径为 top_level_dir

而这个top_level_dir会作为self的参数保存下来,这样第二次运行时 top_level_dir实际取的是上一次的路径,直接影响到了下一次的运行
因此规避此问题的方法
1 要么在一次运行过程中只调用一次 discover

2 如果一定要调用两次,第二次需要手动将 top_level_dir这个参数传给discover方法,这样才能运行不同文件夹下的用例

即修改为

discover = unittest.defaultTestLoader.discover(test_dir, pattern=testClassName, top_level_dir = self.common.getMainPath())     
原网站

版权声明
本文为[觅梦_feng]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43820813/article/details/126226536