我对python测试非常陌生。帮助此方法解释单元测试

2024-05-08 11:52:57 发布

您现在位置: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

Tags: theto函数inputdefloginfunctionmember
1条回答
网友
1楼 · 发布于 2024-05-08 11:52:57

我假设您想为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()的调用的返回值重新定义为"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-框架可以利用更多的选项和可能性

相关问题 更多 >