I want to create unittests for my command line interface
build with the Python prompt-toolkit
(https://github.com/jonathanslenders/python-prompt-toolkit).
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
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 forraw_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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With