- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想为我的命令行界面创建单元测试使用 Python prompt-toolkit
( https://github.com/jonathanslenders/python-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
最佳答案
你可以 mock提示调用。
应用文件
from prompt_toolkit import prompt
def word():
result = prompt('type a word')
return result
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()
请注意,您应该从 app.py 中模拟提示,而不是从 prompt_toolkit 中模拟提示,因为您想拦截来自文件的调用。
根据docstring module :
If you are using this library for retrieving some input from the user (as a pure Python replacement for GNU readline), probably for 90% of the use cases, the :func:
.prompt
function is all you need.
作为method docstring说:
Get input from the user and return it. This is a wrapper around a lot of
prompt_toolkit
functionality and can be a replacement forraw_input
. (or GNU readline.)
在 Getting started 之后来自项目:
>>> 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'>
由于 prompt
方法返回字符串类型,您可以使用 mock.return_value
来模拟用户与您的应用程序的集成。
关于python - 如何为 python 提示工具包创建单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38975025/
我是一名优秀的程序员,十分优秀!