如何使用python glob对简单函数进行DRYer测试?

我有一个功能,搜索一个文件在当前位置,然后在下载文件夹,如果没有找到,引发和错误。使用pytest和pytest-mock,我能够用比测试代码大得多的代码来测试代码。有没有办法让这个更紧/更干?

测试代码:

# cei.py
import glob
import os

def get_xls_filename() -> str:
    """ Returns first xls filename in current folder or Downloads folder """
    csv_filenames = glob.glob("InfoCEI*.xls")
    if csv_filenames:
        return csv_filenames[0]
    home = os.path.expanduser("~")
    csv_filenames = glob.glob(home + "/Downloads/InfoCEI*.xls")
    if csv_filenames:
        return csv_filenames[0]
    return sys.exit(
        "Error: file not found."
    )

这里有三个测试场景。在当前中找到,在下载中找到,但找不到。测试代码:

# test_cei.py
from unittest.mock import Mock

import pytest
from pytest_mock import MockFixture

import cei

@pytest.fixture
def mock_glob_glob_none(mocker: MockFixture) -> Mock:
    """Fixture for mocking glob.glob."""
    mock = mocker.patch("glob.glob")
    mock.return_value = []
    return mock

@pytest.fixture
def mock_os_path_expanduser(mocker: MockFixture) -> Mock:
    """Fixture for mocking os.path.expanduser."""
    mock = mocker.patch("os.path.expanduser")
    mock.return_value = "/home/user"
    return mock

def test_get_xls_filename_not_found(mock_glob_glob_none, mock_os_path_expanduser) -> None:
    with pytest.raises(SystemExit):
        assert cei.get_xls_filename()
        mock_glob_glob_none.assert_called()
        mock_os_path_expanduser.assert_called_once()

@pytest.fixture
def mock_glob_glob_found(mocker: MockFixture) -> Mock:
    """Fixture for mocking glob.glob."""
    mock = mocker.patch("glob.glob")
    mock.return_value = ["/my/path/InfoCEI.xls"]
    return mock

def test_get_xls_filename_current_folder(mock_glob_glob_found) -> None:
    assert cei.get_xls_filename() == "/my/path/InfoCEI.xls"
    mock_glob_glob_found.assert_called_once()

@pytest.fixture
def mock_glob_glob_found_download(mocker: MockFixture) -> Mock:
    """Fixture for mocking glob.glob."""
    values = {
        "InfoCEI*.xls": [],
        "/home/user/Downloads/InfoCEI*.xls": ["/home/user/Downloads/InfoCEI.xls"],
    }

    def side_effect(arg):
        return values[arg]
    mock = mocker.patch("glob.glob")
    mock.side_effect = side_effect
    return mock


def test_get_xls_filename_download_folder(
    mock_glob_glob_found_download, mock_os_path_expanduser
) -> None:
    assert cei.get_xls_filename() == "/home/user/Downloads/InfoCEI.xls"
    mock_os_path_expanduser.assert_called_once()
    mock_glob_glob_found_download.assert_called_with(
        "/home/user/Downloads/InfoCEI*.xls"
    )

转载请注明出处:http://www.hjsszs.com/article/20230526/955594.html