如何对返回相对路径的Python函数进行单元测试?

问题描述 投票:-1回答:1

我编写了一个Python函数,该函数为数据集生成文件路径。我想为该功能包括一个doctest。但是,由于每台计算机都具有不同的相对文件路径,所以我不确定如何编写测试以使其通过任何计算机。

import os

def get_dataset_file_path(date, filename):
    """Produces a filepath for the dataset.

    :parameter date (string): The date folder name.  Ex: "2020-02-05"
    :parameter filename (string): The csv filename.
    :returns filepath (string): The filepath for the dataset.

    Example:

    project_root
    ├── README.md
    ├── data
    │   └── 2020-04-13
    │       ├── README.md
    │       ├── data_description.txt
    │       ├── test.csv
    │       └── train.csv
    ├── docs
    ├── requirements.yml
    └── results
        └── 2020-04-13
            └── runall.py

    The function is called from the 'runall.py' file.
    >>> get_data_file_path('2020-04-13', 'train.csv')
    '~/project_root/data/2020-04-13/train.csv'
    """

    basepath = os.path.abspath('')
    filepath = os.path.abspath(os.path.join(basepath, "..", "..")) + "/data/" + date + "/" + filename
    return filepath
python filepath doctest
1个回答
1
投票

我会mock os.path.abspath

具体取决于您的测试框架。我更喜欢pytestpytest-mock,并且会这样写:

def get_dataset_file_path(mocker):
    mocked_abspath = mocker.patch('os.path.abspath')
    mocked_abspath.return_value = '/project_root/'
    assert get_data_file_path('2020-04-13', 'train.csv') == '/project_root/data/2020-04-13/train.csv'
© www.soinside.com 2019 - 2024. All rights reserved.