【问题标题】:How to create unittests for python prompt toolkit?如何为 python 提示工具包创建单元测试?
【发布时间】:2016-08-20 08:53:03
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    你可以mock提示电话。

    app_file

    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

    如果您使用此库来检索用户的某些输入(作为 GNU readline 的纯 Python 替代品),可能适用于 90% 的用例, :func:.prompt 函数就是你所需要的。

    正如method docstring 所说:

    从用户那里获取输入并返回。 这是对许多 prompt_toolkit 功能的封装,可以替代 raw_input。 (或 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 来模拟用户与您的应用程序的集成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 2016-07-16
      • 1970-01-01
      相关资源
      最近更新 更多