首页 > 解决方案 > 我对python测试很陌生。帮助这个方法解释单元测试

问题描述

该函数将接受输入并根据输入调用登录函数。

def login_features():
print("Choose option to login")
print("1. BDO login")
print("2. GPM login")
print("3. Member login")
login_input = int(input())
switcher = {
    1: bdo_login,
    2: gpm_login, # I am calling the function instance
    3: member_login
}
login = switcher.get(login_input, login_features)
login() # Executing the called function

标签: pythonunit-testingmocking

解决方案


我假设您想为login_features(). 一般来说,我会这样重构函数:

def execute_login_option(opt_str: str):
    switcher = {...}
    login = switcher.get(login_input, login_features)
    login() # Executing the called function

def login_features():
    print("Choose option to login")
    print("1. BDO login")
    print("2. GPM login")
    print("3. Member login")
    login_input = int(input())
    execute_login_option(login_input)

这样您就可以轻松地进行测试execute_login_option而无需修补input().

如果你需要产生一些输入,你可以使用 Python 的unittest.mock.patch

def my_function_with_input():
    test = input("please enter a value")
    return test

with mock.patch('%s.input' % __name__) as patched_input:
    patched_input.return_value = "foo"
    assert my_function_with_input() == "foo"

在上下文中,我将调用的返回值重新定义input()为 be "foo"。同样,您可以在测试用例中将返回值设置为所需的用户输入login_features


编辑(回答评论中关于如何测试不返回值的函数的问题):

如果您的函数没有返回要断言的值,它通常会将整个系统的状态更改为副作用(在您的示例中,这样的副作用可能是用户已登录)。请参阅下面有关如何在此类设置中进行测试的最小示例:

from unittest import mock

class ClassToTest:
    def __init__(self):
        self.state = "A"

    def my_function_with_input(self):
        test = input("please enter a value")
        if test == "foo":
            self.state = "B"
        else:
            self.state = "C"

def my_function_with_input():
    test = input("please enter a value")
    return test

with mock.patch('%s.input' % __name__) as patched_input:
    patched_input.return_value = "foo"

    test_obj = ClassToTest()
    assert test_obj.state == "A"

    test_obj.my_function_with_input()
    assert test_obj.state == "B"  # assert that the state changed to B

使用unittest.mock -framework可以利用更多的选项和可能性。


推荐阅读