久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

python在單元測試中模擬原始輸入

python mocking raw input in unittests(python在單元測試中模擬原始輸入)
本文介紹了python在單元測試中模擬原始輸入的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!

問題描述

假設(shè)我有這個 python 代碼:

Suppose I have this python code:

def answer():
    ans = raw_input('enter yes or no')
    if ans == 'yes':
        print 'you entered yes'
    if ans == 'no':
        print 'you entered no'

如何為此編寫單元測試?我知道我必須使用模擬",但我不明白如何.誰能舉個簡單的例子?

How do I write a unittest for this ? I know i have to use 'Mock' but I don't understand how. Can anyone make some simple example ?

推薦答案

你不能給輸入打補(bǔ)丁,但是你可以把它包裝起來使用 mock.patch().這是一個解決方案:

You can't patch input but you can wrap it to use mock.patch(). Here is a solution:

from unittest.mock import patch
from unittest import TestCase


def get_input(text):
    return input(text)


def answer():
    ans = get_input('enter yes or no')
    if ans == 'yes':
        return 'you entered yes'
    if ans == 'no':
        return 'you entered no'


class Test(TestCase):

    # get_input will return 'yes' during this test
    @patch('yourmodule.get_input', return_value='yes')
    def test_answer_yes(self, input):
        self.assertEqual(answer(), 'you entered yes')

    @patch('yourmodule.get_input', return_value='no')
    def test_answer_no(self, input):
        self.assertEqual(answer(), 'you entered no')

請記住,此代碼段僅適用于 Python 3.3+ 版本

Keep in mind that this snippet will only work in Python versions 3.3+

這篇關(guān)于python在單元測試中模擬原始輸入的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

How should I verify a log message when testing Python code under nose?(在鼻子下測試 Python 代碼時,我應(yīng)該如何驗證日志消息?)
Patch __call__ of a function(修補(bǔ)函數(shù)的 __call__)
How to call self in a mock method of an object in Python?(如何在 Python 中對象的模擬方法中調(diào)用 self?)
Mocking only a single method on an object(僅模擬對象上的單個方法)
Mocking a subprocess call in Python(在 Python 中模擬子進(jìn)程調(diào)用)
Checking call order across multiple mocks(檢查多個模擬的調(diào)用順序)
主站蜘蛛池模板: 免费在线观看av | 亚洲欧美在线播放 | 精品亚洲一区二区三区四区五区 | 国产一级免费 | 91欧美激情一区二区三区成人 | 午夜aaa| 一级黄色片免费看 | 免费性视频 | 91av免费观看 | 中文字幕免费看 | 91久久国产综合久久91 | 欧美一区二区三区在线 | 日本三极片 | 亚洲天堂免费 | 亚洲福利网 | 欧美三级韩国三级日本三斤在线观看 | 午夜99 | 高清乱码男女免费观看 | 亚洲第一黄色 | www超碰| 欧美一级在线 | 亚洲精品网站在线观看 | 青青草福利视频 | 四虎看片 | 丁香婷婷在线 | 国产天堂av| 一级黄片毛片 | 草久久 | 日韩毛片免费看 | 国产三级在线播放 | 久久av网站| 伊人久久综合 | 亚欧在线观看 | 日本一级淫片色费放 | 国产中文字幕在线 | 中文字幕免费av | 欧美日韩一区二区三区 | 精品国产乱码一区二区三 | 精品视频网 | 一级片av | 成年人的免费视频 |