python - CircleCI - pytest 找不到测试使用的文件

标签 python pytest circleci tox

我正在使用 tox 在 CircleCI 部署中运行测试。我有一个名为 tests 的目录,在这个目录中,我有另一个名为 test_files 的目录,其中包含我用于模拟的文件,例如包含 JSON 数据的文件。在本地,我使用模拟文件成功运行测试,但在 CircleCI 中,pytest 无法在目录中找到 JSON 文件:FileNotFoundError: [Errno 2] No such file or directory: 'test_files/data.json'

这是我的tox.ini:

[tox]
envlist = py37,py38,flake8

[testenv]
deps=-r{toxinidir}/requirements.txt
     -r{toxinidir}/test-requirements.txt

commands=
   pytest -v tests

和我的config.yml:

version: 2
jobs:
  # using tox
  toxify:

      docker:
        - image: python:3.8

      steps:
        - checkout
        - run:
            name: tox build
            command: |
              pip install tox
              tox -q
        - run:
            name: deploy
            command: |
              ./deploy.sh
workflows:
  version: 2
  build_and_release:
    jobs:
      - toxify:
          filters:
            tags:
              only: /^v\d+\.\d+\.\d+$/

测试示例:

from my_package.image import ImageValidator

def test_valid_image():
    image_validator = ImageValidator("test_files/default_image.png")
    assert image_validator.is_valid_image() is True

我打开图像:

file_path = glob.glob(os.path.join(os.path.dirname(file_path), '*.png'))[0]
with open(file_path, "rb") as image:
    image_data = image.read()
    ...

我错过了什么吗?

最佳答案

重申注释:如果您在代码中使用相对路径:

def test_valid_image():
    image_validator = ImageValidator("test_files/default_image.png")

路径test_files/default_image.png将相对于当前工作目录进行解析,因此如果完整路径是例如

/root/tests/test_files/default_image.png

仅当您从 /root/tests 运行测试时才能找到该文件: cd/root/tests; pytest 可以工作,而其他所有工作目录,例如cd/root; pytest 测试/ 将失败。这是您的 tox 配置中当前发生的情况:

commands=
   pytest -v tests

在项目根目录中启动pytest,在tests目录中查找测试,因此test_files/default_image.png解析为项目根目录/test_files/default_image.png 而不是您所期望的 project root/tests/test_files/default_image.png

有很多方法可以规避这个问题。最好是解析相对于某些静态文件的路径,例如调用模块:

def test_valid_image():
    path = os.path.join(__file__, '..', '..', 'test_files', 'default_image.png')
    image_validator = ImageValidator(path)

或者,通过知道 pytest 在其配置中存储项目根:

def test_valid_image(request):
    rootdir = request.config.rootdir
    path = os.path.join(rootdir, 'tests', 'test_files', 'default_image.png')
    image_validator = ImageValidator(path)

现在,路径将被解析,忽略工作目录并绑定(bind)到始终具有相同路径的文件;运行pytest测试/cd测试/; pytest 现在具有相同的效果。

其他方法是更改​​工作目录。由于您的测试期望从 tests 目录执行,因此在 tox.ini 中导航到它:

commands=
    cd tests && pytest; cd ..

commands=
    pushd tests; pytest; popd

等等

关于python - CircleCI - pytest 找不到测试使用的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58901734/

相关文章:

python - 使用 websocket-client 连接时出现 WinError 10057

python - 当您打开文件夹时,VS Code 如何处理文件位置?

python - 读取大文本文件和内存

python - 有没有办法指定从文件运行哪些 pytest 测试?

javascript - 为什么node_modules在构建后不断从docker中消失?

python - 从数据框中删除所有标点符号,除了一些字符

python-3.x - Pytest 用户输入模拟

python - 在 Azure DevOps 管道中找不到 Pytest

rspec - 在 circleCI 上创建 tmp 文件的规范失败

android - CircleCI 可以为 Android 项目做单元/浓缩咖啡测试吗?