使用 py.test 模拟 "nosetests -w working-dir" 行为

Emulating "nosetests -w working-dir" behavior using py.test

我正在将一系列测试从 nosetests + python unittest 移植到 py.test。我惊喜地得知 py.test 支持 python unittests 并且 运行 使用 py.test 进行现有测试就像调用 py.test 一样简单nosetests 在命令行上。但是,我在为测试指定 working directory 时遇到问题。它们不在根项目目录中,而是在子目录中。目前的测试是 运行 这样的:

$ nosetests -w test-dir/ tests.py

将当前工作目录更改为 test-dir 和 运行 tests.py 中的所有测试。但是当我使用 py.test

$ py.test test-dir/tests.py

tests.py中的所有测试都是运行,但当前工作目录没有更改为test-dir。大多数测试假设工作目录是 test-dir 并尝试打开并从中读取文件,但显然失败了。

所以我的问题是如何在使用 py.test.

时更改所有测试的当前工作目录

有很多测试,我不想花时间来修复它们并使它们无论 cwd 都能正常工作。

是的,我可以简单地做 cd test-dir; py.test tests.py,但我习惯于在项目根目录下工作,不想每次我想 运行 测试时都 cd。

下面是一些代码,可以让您更好地了解我要实现的目标:

tests.py的内容:

import unittest
class MyProjectTestCase(unittest.TestCase):
  def test_something(self):
      with open('testing-info.txt', 'r') as f:
          test something with f

目录布局:

my-project/
   test-dir/
       tests.py
       testing-info.txt

然后当我尝试 运行 测试时:

$ pwd
my-project
$ nosetests -w test-dir tests.py
# all is fine
$ py.test ttest-dir/tests.py
# tests fail because they cannot open testing-info.txt

所以这是我能想到的最好的:

# content of conftest.py
import pytest
import os

def pytest_addoption(parser):
    parser.addoption("-W", action="store", default=".",
        help="Change current working dir before running the collected tests.")

def pytest_sessionstart(session):
    os.chdir(session.config.getoption('W'))

然后 运行 测试

$ py.test -W test-dir test-dir/tests.py

它不干净,但在我修复所有测试之前它会起作用。