如何为python prompt toolkit创建unittests?

Jon*_*Jon 12 python python-3.x

我想使用Python prompt-toolkit(https://github.com/jonathanslenders/python-prompt-toolkit)为我的命令行界面构建创建单元测试.

  • 如何使用prompt-toolkit模拟用户交互?
  • 这些单元测试是否有最佳实践?

示例代码:

from os import path
from prompt_toolkit import prompt

def csv():
    csv_path = prompt('\nselect csv> ')
    full_path = path.abspath(csv_path)
    return full_path
Run Code Online (Sandbox Code Playgroud)

Mau*_*ldi 10

你可以模拟提示调用.

app_file

from prompt_toolkit import prompt

def word():
    result = prompt('type a word')
    return result
Run Code Online (Sandbox Code Playgroud)

test_app_file

import unittest
from app import word
from mock import patch

class TestAnswer(unittest.TestCase):
    def test_yes(self):
        with patch('app.prompt', return_value='Python') as prompt:
            self.assertEqual(word(), 'Python')
            prompt.assert_called_once_with('type a word')

if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

只是注意你应该从app.py而不是来自prompt_toolkit模拟提示,因为你想拦截来自文件的调用.

根据docstring模块:

如果你使用这个库来检索用户的一些输入(作为GNU readline的纯Python替换),可能是90%的用例,.prompt你需要:func:function.

正如docstring的方法所说:

获取用户的输入并将其返回.这是许多prompt_toolkit功能的包装,可以替代raw_input.(或GNU readline.)

入门的项目:

>>> from prompt_toolkit import prompt
>>> answer = prompt('Give me some input: ')
Give me some input: Hello World
>>> print(answer)
'Hello World'
>>> type(answer)
<class 'str'>
Run Code Online (Sandbox Code Playgroud)

prompt方法返回字符串类型时,您可以使用mock.return_value模拟用户与应用程序的集成.