如何在sentinel while循环中使用PyTest测试输入列表

2024-04-24 07:08:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试使用这个函数测试Pytest中的输入列表

def test_play_hand():                                                               
    word_list = load_words()                                                        
    hand = {'e': 2, 'u': 1, 'g': 1, 'm': 1, 'b': 1, 't': 1}                         
    inputs = ['gum', 'beet', '.']                                                   

    with mock.patch('builtins.input', return_value= next(iter(inputs))):                                                                      
        assert play_hand(hand, word_list) == 0  

函数play\u hand运行一个基于sentinel的while循环,获取一个字典,然后请求用户输入一个字符串。你知道吗

如果输入是.,则循环结束。你知道吗

否则,如果循环得到一个字符串,它将检查指针和可用字符,并从指针中删除字符串中使用的字符。你知道吗

测试工作时模拟补丁只获取一个输入。你知道吗

如何使用列表或多个测试输入来实现测试?你知道吗

如果没有iter(),它会给出一个不可iterable的输入错误,如果没有iter(),它就会冻结。你知道吗

我很感激你的意见。你知道吗

编辑:忘记提到play\u hand返回int


Tags: 函数字符串test列表playpytestdefload
1条回答
网友
1楼 · 发布于 2024-04-24 07:08:17

找到了答案。你知道吗

def test_play_hand():                                                               
    word_list = load_words()                        
    hand = {'e': 2, 'u': 1, 'g': 1, 'm': 1, 'b': 1, 't': 1} 
    inputs = ['gum', 'beet', '.']                                      

    with mock.patch('builtins.input', side_effect = inputs) :                       
        assert play_hand(hand, word_list) == 12 

我不得不用side_effect替换return_value,以运行测试中的所有输入。你知道吗

链接:https://docs.python.org/3/library/unittest.mock.html

相关问题 更多 >