为了账号安全,请及时绑定邮箱和手机立即绑定

我对python测试很陌生。帮助这个方法解释单元测试

我对python测试很陌生。帮助这个方法解释单元测试

白衣非少年 2022-07-05 15:31:42
该函数将接受输入并根据输入调用登录函数。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
查看完整描述

1 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

我假设您想为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可以利用更多的选项和可能性。


查看完整回答
反对 回复 2022-07-05
  • 1 回答
  • 0 关注
  • 127 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号