从不同的工作目录运行时,如何使python单元测试始终找到测试数据文件? [英] How to make python unit tests always find test data files when run from different working directories?
问题描述
这是一个关于测试环境设置的问题.
This is a question about testing environment setup.
在我的项目中,我有一些访问测试数据文件的单元测试.这些单元测试可以通过测试运行器从我的项目目录运行.或者我可以单独运行每个测试文件/模块,例如出于调试目的.
In my project, I have a few unit tests that access test data files. These unit tests can be run from my project directory via a test runner. Or I can run each test file/module individually, for debugging purposes, for instance.
问题是,根据我运行测试的位置,当前目录是不同的.因此,当从项目目录运行这些文件时,通过提供相对于当前目录的路径来打开测试数据文件(如下所示)将不起作用,因为测试数据文件不在该目录中.
The problem is that depending on where I run the tests from, the current directory is different. So opening a test data file, as below, by giving a path relative to the current directory will not work when those files are run from the project directory, as the test data file is not in that directory.
f = open('test_data.ext', 'r')
我想使用 __file__ 来使用相对于当前测试模块的路径,但是当测试模块调用 __file__ 时,这个 不起作用是单独运行的.
I thought of using __file__ to use a path relative the current test module, but this doesn't work when the test module calling __file__ is the one being run individually.
人们一般是如何解决这个问题的?
How do people generally solve this problem?
推荐答案
想到了许多不同的方法:
A number of different ways come to mind:
- 为您的数据目录设置环境变量
- 编写一个始终导入的小模块,其唯一目的是拥有相对于数据目录的固定位置,然后从那里调用
__file__
- 在运行时生成数据
- 将数据存储在数据库而不是文件中
- 将您的数据存储在文件系统中的固定位置,而不是相对于包的位置
- 不要直接运行测试代码
最适合您的解决方案取决于您的环境以及您的特定数据和程序.
The solution that makes the most sense for you depends upon your environment and your specific data and program.
这篇关于从不同的工作目录运行时,如何使python单元测试始终找到测试数据文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!