第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我對python測試很陌生。幫助這個方法解釋單元測試

我對python測試很陌生。幫助這個方法解釋單元測試

白衣非少年 2022-07-05 15:31:42
該函數(shù)將接受輸入并根據(jù)輸入調(diào)用登錄函數(shù)。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條經(jīng)驗 獲得超4個贊

我假設(shè)您想為login_features(). 一般來說,我會這樣重構(gòu)函數(shù):


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().


如果你需要產(chǎn)生一些輸入,你可以使用 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"

在上下文中,我將調(diào)用的返回值重新定義input()為 be "foo"。同樣,您可以在測試用例中將返回值設(shè)置為所需的用戶輸入login_features。


編輯(回答評論中關(guān)于如何測試不返回值的函數(shù)的問題):


如果您的函數(shù)沒有返回要斷言的值,它通常會將整個系統(tǒng)的狀態(tài)更改為副作用(在您的示例中,這樣的副作用可能是用戶已登錄)。請參閱下面有關(guān)如何在此類設(shè)置中進行測試的最小示例:


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可以利用更多的選項和可能性。


查看完整回答
反對 回復(fù) 2022-07-05
  • 1 回答
  • 0 關(guān)注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號