Python 单元测试不是来自指定目录的 运行

Python unittest not running from specified directory

如果我 运行 这个命令在 app 里面,我得到这个错误,指出没有这样的文件或目录:

python3 -m unittest discover -t ~/app/dataloader/  -s ~/app/dataloader/tests

导致此错误:

  with open("assertions/validator/validation_config.json") as inp:
FileNotFoundError: [Errno 2] No such file or directory: 'assertions/validator/validation_config.json'

但是,如果我 cd 到 dataloader 和 运行 中:

python3 -m unittest discover -t .  -s tests

一切都会过去。

这很奇怪吗?

app文件夹结构为app -> dataloader -> assertions -> validator -> validation_config.json

我认为unittest discover-t-s选项分别对应unittest.TestLoader.discovertop_level_dirstart_dir参数

Find all the test modules by recursing into subdirectories from the specified start directory, and return a TestSuite object containing them...

All test modules must be importable from the top level of the project. If the start directory is not the top level directory then the top level directory must be specified separately.

所以这两个选项控制了 unittest 在测试时如何查找和导入模块。但是,它们似乎不会影响程序在运行时搜索文件的方式。如果你在加载 validation_config.json 之前打印出 os.listdir(),你会发现只有后一种情况能够通过相对路径找到它。

要解决该问题,您可以使用 os.path.abspath 将该行修改为绝对路径,例如:

# Get the absolute path of this current test script
base_path, _ = os.path.split(os.path.abspath(__file__))
# Form the absolute path of the needed json
json_path = os.path.join(base_path, "../assertions/validator/validation_config.json")

with open(json_path) as inp:
    validation_config = json.load(inp)

那么您之前的案例也应该有效。