gpt4 book ai didi

python - 如何为 python 提示工具包创建单元测试?

转载 作者:太空狗 更新时间:2023-10-29 17:48:00 25 4
gpt4 key购买 nike

我想为我的命令行界面创建单元测试使用 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 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 来模拟用户与您的应用程序的集成。

关于python - 如何为 python 提示工具包创建单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38975025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com