当使用 tox 运行 时,如何使 pytest 测试可以访问测试数据文件?

How can I make test data files accessible to pytest tests when run with tox?

我想 运行 一个接受 Path to a file as input via an argument: function(some_path_to_file) via tox. The file I want to pass to the function cannot be created temporarily during test setup (what I usually do via pytests builtin tmpdir fixtures) but resides in the package <package>/data directory besides the test directory <package>/tests (the location <package>/tests/data would probably be better). Because tox runs the tests in a virtualenv it's not clear to me how to make the test data file available to the test. I know that I can define the base temporary directory of pytest with the --basedir option 的函数的 test 但我还没有让它与 tox 一起工作。

tl;dr

问题是 some_path_to_filePathstr 的转换(将其传递给 sqlite3.connect(database inside the function) using Path.resolve()。无需配置 pytests --basedir 选项和 tox 以任何方式。

tox 预定义 substitutions 个数。 virtualenv 的目录是 {envdir}site-packages{envsitepackagesdir}。将命令行中的值传递给您的测试脚本,如下所示:

[testenv]
    commands = pytest --basedir={envsitepackagesdir}/mypackage

这也把我绊倒了。我能够解决它的方法是 指定文本文件的完整路径 我希望测试函数读取 relative 到基本目录.

例如,我的目录树如下所示:

.
├── __init__.py
├── my_package
│   ├── __init__.py
│   └── calculate_stats.py
├── my_package.egg-info
│   ├── PKG-INFO
│   ├── SOURCES.txt
│   ├── dependency_links.txt
│   ├── requires.txt
│   └── top_level.txt
├── bin
│   └── calculate_stats
├── requirements
│   ├── default.txt
│   └── development.txt
├── setup.py
├── test
│   ├── __init__.py
│   ├── test_calculate_stats.csv
│   ├── test_calculate_stats.txt
│   └── test_calculate_stats.py
└── tox.ini

在文件 test_calculate_stats.py 中,我有以下行:

assert (calculate_stats.calculate_stats_to_csv("test/test_calculate_stats.txt", "test/test_calculate_stats.csv") == 60)

calculate_stats_to_csv函数读取test/test_calculate_stats.txt文件,计算一些统计数据,输出到test/test_calculate_stats.csv

最初我只是将输入文件指定为 test_calculate_stats.txt,因为它与包含测试函数的文件位于同一目录中 - 那是我 运行 进入错误的时候。