你如何正确地将文件解析的单元测试与pytest集成?

Chr*_*ley 3 python unit-testing pytest python-2.7

我正在尝试用pytest测试文件解析.我有一个目录树,对我的项目看起来像这样:

project
    project/
        cool_code.py
    setup.py
    setup.cfg
    test/
        test_read_files.py
        test_files/
            data_file1.txt
            data_file2.txt
Run Code Online (Sandbox Code Playgroud)

我的setup.py文件看起来像这样:

from setuptools import setup

setup(
    name           = 'project',
    description    = 'The coolest project ever!',
    setup_requires = ['pytest-runner'],
    tests_require  = ['pytest'],
    )
Run Code Online (Sandbox Code Playgroud)

我的setup.cfg文件看起来像这样:

[aliases]
test=pytest
Run Code Online (Sandbox Code Playgroud)

我用pytest编写了几个单元测试来验证文件是否正确读取.当我从" test "目录中运行pytest时,它们工作正常.但是,如果我从项目目录中执行以下任何操作,测试将失败,因为它们无法在test_files中找到数据文件:

>> py.test
>> python setup.py pytest
Run Code Online (Sandbox Code Playgroud)

测试似乎对执行pytest的目录很敏感.

当我从测试目录或项目根目录调用它时,如何通过pytest单元测试来发现"data_files"中的文件进行解析?

the*_*man 6

一种解决方案是rootdir使用指向测试目录的路径定义夹具,并引用与此相关的所有数据文件.这可以通过test/conftest.py使用如下代码创建(如果尚未创建)来完成:

import os
import pytest

@pytest.fixture
def rootdir():
    return os.path.dirname(os.path.abspath(__file__))
Run Code Online (Sandbox Code Playgroud)

然后os.path.join在测试中使用以获取测试文件的绝对路径:

import os

def test_read_favorite_color(rootdir):
    test_file = os.path.join(rootdir, 'test_files/favorite_color.csv')
    data = read_favorite_color(test_file)
    # ...
Run Code Online (Sandbox Code Playgroud)