【问题标题】:How to unit test Python function that returns a relative path?如何对返回相对路径的 Python 函数进行单元测试?
【发布时间】:2020-04-13 14:02:14
【问题描述】:

我编写了一个 Python 函数,它为数据集生成文件路径。我想为该函数添加一个文档测试。但是,由于每台机器都有不同的相对文件路径,我不确定如何编写测试以便它可以在任何机器上通过。

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】:

我会mockos.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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多