如何创建unittestsforpython提示工具包?

2024-10-17 06:24:06 发布

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

我想为我的命令行界面创建单元测试 使用Pythonprompt-toolkithttps://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

Tags: csvpath命令行fromhttpsimportgithubcom
1条回答
网友
1楼 · 发布于 2024-10-17 06:24:06

您可以mock调用提示。在

应用程序文件

from prompt_toolkit import prompt

def word():
    result = prompt('type a word')
    return result

测试应用程序文件

^{pr2}$

只需注意一点,您应该模仿中的提示应用程序副本,而不是来自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 for raw_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来模拟用户与应用程序的集成。在

相关问题 更多 >