使用 pytest 在 Python 中编写函数测试

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

我有一个没有输入参数的函数。有没有办法编写Python代码来使用pytest测试该函数?

这是功能,这是一个简单的菜单选择:

def show_menu()->int:
    '''
    Print out the options to select and prompt the user for selecting one in the main menu,
    validating the user input via regex pattern and return the int of user input.
    '''
    print("\n1. Add Transaction", "2. Show Report", "3. Show Plot", "4. Export Transactions.csv",
        "5. Exit\n", sep="\n")
    while True:
        choice = input("\x1b[1;34;40m"+">>> What would you like to do? (Enter number): "+"\x1b[0m")
        search = re.search(r"^\s*[1-5]{1}\s*$", choice)
        if search:
            break
        else:
            print("Invalid Input")
            continue
    return int(choice)
python unit-testing pytest
1个回答
0
投票

测试代码能力的程度称为代码的可测试性

您的代码的可测试性不高,因为它包含 I/O 操作(

print
input
)与逻辑(即 rexeg 匹配)位于同一函数中

虽然可以通过诸如 Monkeypaching 或 I/O 流重定向之类的“黑客攻击”来测试执行 I/O 的函数,但通常不建议将其用于单元测试。

流程/E2E/集成测试可能会测试包含 I/O 的组件,但我想这是您的意图。

您可能希望将代码分解为可测试的组件,然后在不测试的单独函数中执行 I/O。

在您的代码中:


def parse_user_choise(choice) -> int | None:
    search = re.search(r"^\s*[1-5]{1}\s*$", choice)
    if not search:
        return None
    
    return int(search)

def show_menu()->int:
    '''
    Print out the options to select and prompt the user for selecting one in the main menu,
    validating the user input via regex pattern and return the int of user input.
    '''
    print("\n1. Add Transaction", "2. Show Report", "3. Show Plot", "4. Export Transactions.csv",
        "5. Exit\n", sep="\n")
    while True:
        choice = input("\x1b[1;34;40m"+">>> What would you like to do? (Enter number): "+"\x1b[0m")
        parsed_choise = parse_user_choise(choice)
        if choice:
            break
        else:
            print("Invalid Input")
            continue
    return parsed_choise

在您的测试模块中:


def test_valid_input():
    assert parse_user_choise("3") == 3


def test_invalid_input():
    assert parse_user_choise("Hello World") == None
© www.soinside.com 2019 - 2024. All rights reserved.