简体   繁体   English

如何为python prompt toolkit创建unittests?

[英]How to create unittests for python prompt toolkit?

I want to create unittests for my command line interface build with the Python prompt-toolkit ( https://github.com/jonathanslenders/python-prompt-toolkit ). 我想使用Python prompt-toolkithttps://github.com/jonathanslenders/python-prompt-toolkit )为我的命令行界面构建创建单元测试。

  • How can I emulate user interaction with the prompt-toolkit? 如何使用prompt-toolkit模拟用户交互?
  • Is there a best practice for these unittests? 这些单元测试是否有最佳实践?

Example Code: 示例代码:

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

You could mock the prompt calls. 你可以模拟提示调用。

app_file app_file

from prompt_toolkit import prompt

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

test_app_file 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()

Just an attention to the point you should mock the prompt from the app.py , not from prompt_toolkit , because you want to intercept the call from the file. 只是注意你应该从app.py而不是来自prompt_toolkit模拟提示,因为你想拦截来自文件的调用。

According with the docstring module : 根据docstring模块

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. 如果您使用此库来检索用户的一些输入(作为GNU readline的纯Python替换),可能对于90%的用例,只需要:func: .prompt函数。

And as method docstring says: 正如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 . 这是许多prompt_toolkit功能的包装,可以替代raw_input (or GNU readline.) (或GNU readline。)

Following the Getting started from project: 入门的项目:

>>> 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'>

As prompt method return a string type, you could use mock.return_value to simulate the user integration with your app. prompt方法返回字符串类型时,您可以使用mock.return_value来模拟用户与您的应用程序的集成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM