Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

  • How can I emulate user interaction with the 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
like image 970
Jon Avatar asked Aug 16 '16 12:08

Jon


1 Answers

You could mock the prompt calls.

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

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.

According with the 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.

And as method docstring says:

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.)

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.

like image 167
Mauro Baraldi Avatar answered Oct 07 '22 17:10

Mauro Baraldi