How to test function that has an input [duplicate] - python

I have a console program written in Python. It asks the user questions using the command:
some_input = input('Answer the question:', ...)
How would I test a function containing a call to input using pytest?
I wouldn't want to force a tester to input text many many times only to finish one test run.

As The Compiler suggested, pytest has a new monkeypatch fixture for this. A monkeypatch object can alter an attribute in a class or a value in a dictionary, and then restore its original value at the end of the test.
In this case, the built-in input function is a value of python's __builtins__ dictionary, so we can alter it like so:
def test_something_that_involves_user_input(monkeypatch):
# monkeypatch the "input" function, so that it returns "Mark".
# This simulates the user entering "Mark" in the terminal:
monkeypatch.setattr('builtins.input', lambda _: "Mark")
# go about using input() like you normally would:
i = input("What is your name?")
assert i == "Mark"

You should probably mock the built-in input function, you can use the teardown functionality provided by pytest to revert back to the original input function after each test.
import module # The module which contains the call to input
class TestClass:
def test_function_1(self):
# Override the Python built-in input method
module.input = lambda: 'some_input'
# Call the function you would like to test (which uses input)
output = module.function()
assert output == 'expected_output'
def test_function_2(self):
module.input = lambda: 'some_other_input'
output = module.function()
assert output == 'another_expected_output'
def teardown_method(self, method):
# This method is being called after each test case, and it will revert input back to original function
module.input = input
A more elegant solution would be to use the mock module together with a with statement. This way you don't need to use teardown and the patched method will only live within the with scope.
import mock
import module
def test_function():
with mock.patch.object(__builtins__, 'input', lambda: 'some_input'):
assert module.function() == 'expected_output'

You can replace sys.stdin with some custom Text IO, like input from a file or an in-memory StringIO buffer:
import sys
class Test:
def test_function(self):
sys.stdin = open("preprogrammed_inputs.txt")
module.call_function()
def setup_method(self):
self.orig_stdin = sys.stdin
def teardown_method(self):
sys.stdin = self.orig_stdin
this is more robust than only patching input(), as that won't be sufficient if the module uses any other methods of consuming text from stdin.
This can also be done quite elegantly with a custom context manager
import sys
from contextlib import contextmanager
#contextmanager
def replace_stdin(target):
orig = sys.stdin
sys.stdin = target
yield
sys.stdin = orig
And then just use it like this for example:
with replace_stdin(StringIO("some preprogrammed input")):
module.call_function()

This can be done with mock.patch and with blocks in python3.
import pytest
import mock
import builtins
"""
The function to test (would usually be loaded
from a module outside this file).
"""
def user_prompt():
ans = input('Enter a number: ')
try:
float(ans)
except:
import sys
sys.exit('NaN')
return 'Your number is {}'.format(ans)
"""
This test will mock input of '19'
"""
def test_user_prompt_ok():
with mock.patch.object(builtins, 'input', lambda _: '19'):
assert user_prompt() == 'Your number is 19'
The line to note is mock.patch.object(builtins, 'input', lambda _: '19'):, which overrides the input with the lambda function. Our lambda function takes in a throw-away variable _ because input takes in an argument.
Here's how you could test the fail case, where user_input calls sys.exit. The trick here is to get pytest to look for that exception with pytest.raises(SystemExit).
"""
This test will mock input of 'nineteen'
"""
def test_user_prompt_exit():
with mock.patch.object(builtins, 'input', lambda _: 'nineteen'):
with pytest.raises(SystemExit):
user_prompt()
You should be able to get this test running by copy and pasting the above code into a file tests/test_.py and running pytest from the parent dir.

Since I need the input() call to pause and check my hardware status LEDs, I had to deal with the situation without mocking. I used the -s flag.
python -m pytest -s test_LEDs.py
The -s flag essentially means: shortcut for --capture=no.

You can do it with mock.patch as follows.
First, in your code, create a dummy function for the calls to input:
def __get_input(text):
return input(text)
In your test functions:
import my_module
from mock import patch
#patch('my_module.__get_input', return_value='y')
def test_what_happens_when_answering_yes(self, mock):
"""
Test what happens when user input is 'y'
"""
# whatever your test function does
For example if you have a loop checking that the only valid answers are in ['y', 'Y', 'n', 'N'] you can test that nothing happens when entering a different value instead.
In this case we assume a SystemExit is raised when answering 'N':
#patch('my_module.__get_input')
def test_invalid_answer_remains_in_loop(self, mock):
"""
Test nothing's broken when answer is not ['Y', 'y', 'N', 'n']
"""
with self.assertRaises(SystemExit):
mock.side_effect = ['k', 'l', 'yeah', 'N']
# call to our function asking for input

I don't have enough points to comment, but this answer: https://stackoverflow.com/a/55033710/10420225
doesn't work if you just copy/pasta.
Part One
For Python3, import mock doesn't work.
You need import unittest.mock and call it as unittest.mock.patch.object(), or from unittest import mock mock.patch.object()...
If using Python3.3+ the above should "just work". If using Python3.3- you need to pip install mock. See this answer for more info: https://stackoverflow.com/a/11501626/10420225
Part Two
Also, if you want to make this example more realistic, i.e. importing the function from outside the file and using it, there's more assembly required.
This is general directory structure we'll use
root/
src/prompt_user.py
tests/test_prompt_user.py
If function in external file
# /root/src/prompt_user.py
def user_prompt():
ans = input("Enter a number: ")
try:
float(ans)
except:
import sys
sys.exit("NaN")
return "Your number is {}".format(ans)
# /root/tests/test_prompt_user.py
import pytest
from unittest import mock
import builtins
from prompt_user import user_prompt
def test_user_prompt_ok():
with mock.patch.object(builtins, "input", lambda _: "19"):
assert user_prompt() == "Your number is 19"
If function in a class in external file
# /root/src/prompt_user.py
class Prompt:
def user_prompt(self):
ans = input("Enter a number: ")
try:
float(ans)
except:
import sys
sys.exit("NaN")
return "Your number is {}".format(ans)
# /root/tests/test_prompt_user.py
import pytest
from unittest import mock
import builtins
from mocking_test import Prompt
def test_user_prompt_ok():
with mock.patch.object(builtins, "input", lambda _: "19"):
assert Prompt.user_prompt(Prompt) == "Your number is 19"
Hopefully this helps people a bit more. I find these very simple examples almost useless because it leaves a lot out for real world use cases.
Edit: If you run into pytest import issues when running from external files, I would recommend looking over this answer: PATH issue with pytest 'ImportError: No module named YadaYadaYada'

A different alternative that does not require using a lambda function and provides more control during the tests is to use the mock decorator from the standard unittest module.
It also has the additional advantage of patching just where the object (i.e. input) is looked up, which is the recommended strategy.
# path/to/test/module.py
def my_func():
some_input = input('Answer the question:')
return some_input
# tests/my_tests.py
from unittest import mock
from path.to.test.module import my_func
#mock.patch("path.to.test.module.input")
def test_something_that_involves_user_input(mock_input):
mock_input.return_value = "This is my answer!"
assert my_func() == "This is my answer!"
mock_input.assert_called_once() # Optionally check one and only one call

The simplest way that works without mocking and easily in doctest for lightweight testing, is just making the input_function a parameter to your function and passing in this FakeInput class with the appropriate list of inputs that you want:
class FakeInput:
def __init__(self, input):
self.input = input
self.index = 0
def __call__(self):
line = self.input[self.index % len(self.input)]
self.index += 1
return line
Here is an example usage to test some functions using the input function:
import doctest
class FakeInput:
def __init__(self, input):
self.input = input
self.index = 0
def __call__(self):
line = self.input[self.index % len(self.input)]
self.index += 1
return line
def add_one_to_input(input_func=input):
"""
>>> add_one_to_input(FakeInput(['1']))
2
"""
return int(input_func()) + 1
def add_inputs(input_func=input):
"""
>>> add_inputs(FakeInput(['1', '5']))
6
"""
return int(input_func()) + int(input_func())
def return_ten_inputs(input_func=input):
"""
>>> return_ten_inputs(FakeInput(['1', '5', '7']))
[1, 5, 7, 1, 5, 7, 1, 5, 7, 1]
"""
return [int(input_func()) for _ in range(10)]
def print_4_inputs(input_func=input):
"""
>>> print_4_inputs(FakeInput(['1', '5', '7']))
1
5
7
1
"""
for i in range(4):
print(input_func())
if __name__ == '__main__':
doctest.testmod()
This also makes your functions more general so you can easily change them to take input from a file rather than the keyboard.

You can also use environment variables in your test code. For example if you want to give path as argument you can read env variable and set default value if it's missing.
import os
...
input = os.getenv('INPUT', default='inputDefault/')
Then start with default argument
pytest ./mytest.py
or with custom argument
INPUT=newInput/ pytest ./mytest.py

Related

How to implement my code to specific unittest [duplicate]

Function foo prints to console. I want to test the console print. How can I achieve this in python?
Need to test this function, has NO return statement :
def foo(inStr):
print "hi"+inStr
My test :
def test_foo():
cmdProcess = subprocess.Popen(foo("test"), stdout=subprocess.PIPE)
cmdOut = cmdProcess.communicate()[0]
self.assertEquals("hitest", cmdOut)
You can easily capture standard output by just temporarily redirecting sys.stdout to a StringIO object, as follows:
import StringIO
import sys
def foo(inStr):
print "hi"+inStr
def test_foo():
capturedOutput = StringIO.StringIO() # Create StringIO object
sys.stdout = capturedOutput # and redirect stdout.
foo('test') # Call unchanged function.
sys.stdout = sys.__stdout__ # Reset redirect.
print 'Captured', capturedOutput.getvalue() # Now works as before.
test_foo()
The output of this program is:
Captured hitest
showing that the redirection successfully captured the output and that you were able to restore the output stream to what it was before you began the capture.
Note that the code above in for Python 2.7, as the question indicates. Python 3 is slightly different:
import io
import sys
def foo(inStr):
print ("hi"+inStr)
def test_foo():
capturedOutput = io.StringIO() # Create StringIO object
sys.stdout = capturedOutput # and redirect stdout.
foo('test') # Call function.
sys.stdout = sys.__stdout__ # Reset redirect.
print ('Captured', capturedOutput.getvalue()) # Now works as before.
test_foo()
This Python 3 answer uses unittest.mock. It also uses a reusable helper method assert_stdout, although this helper is specific to the function being tested.
import io
import unittest
import unittest.mock
from .solution import fizzbuzz
class TestFizzBuzz(unittest.TestCase):
#unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def assert_stdout(self, n, expected_output, mock_stdout):
fizzbuzz(n)
self.assertEqual(mock_stdout.getvalue(), expected_output)
def test_only_numbers(self):
self.assert_stdout(2, '1\n2\n')
Note that the mock_stdout arg is passed automatically by the unittest.mock.patch decorator to the assert_stdout method.
A general-purpose TestStdout class, possibly a mixin, can in principle be derived from the above.
For those using Python ≥3.4, contextlib.redirect_stdout also exists, but it seems to serve no benefit over unittest.mock.patch.
If you happen to use pytest, it has builtin output capturing. Example (pytest-style tests):
def eggs():
print('eggs')
def test_spam(capsys):
eggs()
captured = capsys.readouterr()
assert captured.out == 'eggs\n'
You can also use it with unittest test classes, although you need to passthrough the fixture object into the test class, for example via an autouse fixture:
import unittest
import pytest
class TestSpam(unittest.TestCase):
#pytest.fixture(autouse=True)
def _pass_fixtures(self, capsys):
self.capsys = capsys
def test_eggs(self):
eggs()
captured = self.capsys.readouterr()
self.assertEqual('eggs\n', captured.out)
Check out Accessing captured output from a test function for more info.
You can also use the mock package as shown below, which is an example from
https://realpython.com/lessons/mocking-print-unit-tests.
from mock import patch
def greet(name):
print('Hello ', name)
#patch('builtins.print')
def test_greet(mock_print):
# The actual test
greet('John')
mock_print.assert_called_with('Hello ', 'John')
greet('Eric')
mock_print.assert_called_with('Hello ', 'Eric')
The answer of #Acumenus says:
It also uses a reusable helper method assert_stdout, although this helper is specific to the function being tested.
the bold part seems a big drawback, thus I would do the following instead:
# extend unittest.TestCase with new functionality
class TestCase(unittest.TestCase):
def assertStdout(self, expected_output):
return _AssertStdoutContext(self, expected_output)
# as a bonus, this syntactical sugar becomes possible:
def assertPrints(self, *expected_output):
expected_output = "\n".join(expected_output) + "\n"
return _AssertStdoutContext(self, expected_output)
class _AssertStdoutContext:
def __init__(self, testcase, expected):
self.testcase = testcase
self.expected = expected
self.captured = io.StringIO()
def __enter__(self):
sys.stdout = self.captured
return self
def __exit__(self, exc_type, exc_value, tb):
sys.stdout = sys.__stdout__
captured = self.captured.getvalue()
self.testcase.assertEqual(captured, self.expected)
this allows for the much nicer and much more re-usable:
# in a specific test case, the new method(s) can be used
class TestPrint(TestCase):
def test_print1(self):
with self.assertStdout("test\n"):
print("test")
by using a straight forward context manager. (It might also be desirable to append "\n" to expected_output since print() adds a newline by default. See next example...)
Furthermore, this very nice variant (for an arbitrary number of prints!)
def test_print2(self):
with self.assertPrints("test1", "test2"):
print("test1")
print("test2")
is possible now.
You can also capture the standard output of a method using contextlib.redirect_stdout:
import unittest
from contextlib import redirect_stdout
from io import StringIO
class TestMyStuff(unittest.TestCase):
# ...
def test_stdout(self):
with redirect_stdout(StringIO()) as sout:
my_command_that_prints_to_stdout()
# the stream replacing `stdout` is available outside the `with`
# you may wish to strip the trailing newline
retval = sout.getvalue().rstrip('\n')
# test the string captured from `stdout`
self.assertEqual(retval, "whatever_retval_should_be")
Gives you a locally scoped solution. It is also possible to capture the standard error using contextlib.redirect_stderr().
Another variant is leaning on the logging module rather than print(). This module also has a suggestion of when to use print in the documentation:
Display console output for ordinary usage of a command line script or program
PyTest has built-in support for testing logging messages.

Mock method of an object inside function [python]

I have two files:- file1.py and file2.py
file2.py has following code:-
import json
def fun1():
s = "{'function1': 'val1'}"
s = json.dumps(s)
print("in fun1 ", s)
return s
def fun2():
s = "{'function2': 'value2'}"
s = json.dumps(s)
print("in fun2 ", s)
return s
def fun5():
fun2()
return fun1()
file1.py has following code
from mockito import when, unstub
from file2 import fun5
def mock_the_function():
when("file2.fun1.json").dumps(...).thenReturn("something something")
print(fun5())
unstub()
I want to mock "dumps" inside "fun1" only, not "fun2". Code which I have written is showing error. I don't want to do it by parameter comparison. Is there any other way I can have a function being passed inside "when"?
First a quick note:
json.dumps takes an object, not a string, so it's kind of redundant to to call it as you are inside fun1 and fun2. Perhaps you're looking for json.loads?
Next I'd consider some different approaches:
When you mock json.dumps, you want to mock the the json property of the file2 module, so it would just be when("file2.json")... in the setup code for your test.
Because (as above), we're mocking the json module globally in the file2 module, it's not possible to, as you asked, in that context of a single test, mock json.dumps inside of fun1 but not fun2, but what I'd suggest is to simply have two tests, and unstub in a tear down method. For example:
from unittest import TestCase
class TestExample(TestCase):
def tearDown(self):
unstub()
def test_fun1(self):
when("file2.json").dumps(...).thenReturn("something something")
# in this invocation json is stubbed
self.assertEqual(fun1(), "something something")
def test_fun2(self):
# but now unstub has been called so it won't be stubbed anymore.
self.assertEqual(fun2(), "...output of fun2...")
Another alternative is for fun1 and fun2 to take a function that will do the work that the global json module is currently doing. This use of the Dependency Inversion Principle makes the code more testable, and means you don't even need mockito in your tests. For example:
def fun1(json_decoder):
s = "..."
return json_decoder(s)
# ....
from unittest.mock import MagicMock
def test_fun_1():
mock_decoder = MagicMock()
mock_decoder.return_value = "asdf"
assert fun1(mock_decoder) == "asdf"

Python Unittest; How to get the parameters passed when the function is called?

I am trying to make a unit test to check if this python function (dispatch) passes the correct parameters to deal_with_result.
Is there a way to "hijack" the input parameters when the function deal_with_result is called in dispatch?
I do not have the rights to modify the code in the dispatch function.
Here is a preview of want I want in my unit test:
import maker
from operators import op_morph
import unittest
from unittest.mock import Mock
import cv2
img = cv2.imread("/img_tests/unitTestBaseImage.png")
def my_side_effect(*args, **kwargs):
global img
print(args)
print(kwargs)
if args!=None:
if len(args)>0:
if args[0] == img:
return 0
return 3
else:
return 2
return 1
class TestCalls(unittest.TestCase):
def test_dispatch(self):
global img
makerMock = Mock()
makerMock.deal_with_result.side_effect = my_side_effect
#calling the dispatch function
maker.dispatch(["json_example.json"])
#instead of passing this mock I want to get the real parameters passed
#when the function deal_with_result is called in dispatch.
temp=makerMock.deal_with_result("img")
print("image return code: "+str(temp))
if __name__ == '__main__':
unittest.main(exit=False)
Thank you.
I have been looking for an answer to this whilst at job.Haven't found anything on it. I recommend you to talk your boss into letting you modify the base function so you don't waste precious time and resources.

Is it possible to mock a lambda expression?

The first two functions display_pane_1 and template_1 are easily tested
in the method test_1. I want to refactor these two functions into a single function display_pane_2.
lambdademo.py:
def display_pane_1():
display_register(template_1)
def template_1():
return 'hello mum'
def display_pane_2():
display_register(lambda: 'hello mum')
def display_register(template):
print(template())
test_lambdademo.py
import unittest
import unittest.mock as mock
import lambdademo
class TestLambda1(unittest.TestCase):
def setUp(self):
p = mock.patch('lambdademo.display_register')
self.mock_display_register = p.start()
self.addCleanup(p.stop)
def test_1(self):
lambdademo.display_pane_1()
self.mock_display_register.assert_called_with(lambdademo.template_1)
def test_2(self):
lambdademo.display_pane_2()
self.mock_display_register.assert_called_with('????????')
Can you help me write a valid test for display_pane_2? I would like to test the complete lambda expression i.e. lambda x: 'hell mum' should fail.
I've tried two paths to a solution.
The first option is a simple copy of test_1,replacing the argument of lambdademo.template_1 with a mock of lambda. I couldn't find anything in the manual that suggests how I should mock an expression like lambda.
If it is in the manual please tell me where.
My second option followed from a wider search here on Stack Overflow and out on the Internet. The lack of responsive hits for 'python expression unittest',
'python lambda unittest', 'python expression mock', or 'python lambda mock'
suggested that I may be asking the wrong question. Is my assumption that I will need to mock the lambda expression wrong?
I am aware that a simple coding solution would be to keep the original code but at this point I'm more interested in filling in a gap in my knowledge.
If the lambda expression is accessible somewhere like an attribute of a class or a module, then you could mock it, but that seems very unlikely. Usually, a lambda expression is used when you don't need a reference to the function. Otherwise, you'd just use a regular function.
However, you can retrieve the arguments to all calls on a mock object, so you could look at the lambda expression that was passed in. In an example like the one you gave, the simplest thing to do would just be to call the lambda expression and see what it returns.
from mock import patch
def foo(bar):
return bar()
def baz():
return 42
print foo(baz)
with patch('__main__.foo') as mock_foo:
print foo(baz)
print foo(lambda: 'six by nine')
assert mock_foo.call_args_list[0][0][0]() == 42
assert mock_foo.call_args_list[1][0][0]() == 'six by nine'
If for some reason you don't want to do that, then you could use the inspect module to look at the lambda expression. Here's an example that just dumps the source code lines where the function was defined:
from inspect import getsource
from mock import patch
def foo(bar):
return bar()
def baz():
return 42
print foo(baz)
with patch('__main__.foo') as mock_foo:
print foo(baz)
print foo(lambda: 'six by nine')
print mock_foo.call_args_list
for call_args in mock_foo.call_args_list:
print '---'
print getsource(call_args[0][0])
The results:
42
<MagicMock name='foo()' id='140595519812048'>
<MagicMock name='foo()' id='140595519812048'>
[call(<function baz at 0x7fdef208fc08>),
call(<function <lambda> at 0x7fdef208fe60>)]
---
def baz():
return 42
---
print foo(lambda: 'six by nine')
Here is a version of your test that passes with your example code. It tests both ways: calling the template and inspecting the source of the template.
# test_lambdademo.py
from inspect import getsource
import unittest
import unittest.mock as mock
import lambdademo
class TestLambda1(unittest.TestCase):
def setUp(self):
p = mock.patch('lambdademo.display_register')
self.mock_display_register = p.start()
self.addCleanup(p.stop)
def test_1(self):
lambdademo.display_pane_1()
self.mock_display_register.assert_called_with(lambdademo.template_1)
def test_2(self):
lambdademo.display_pane_2()
template = self.mock_display_register.call_args[0][0]
template_content = template()
template_source = getsource(template)
self.assertEqual('hello mum', template_content)
self.assertIn('hello mum', template_source)

How to test a function with input call?

I have a console program written in Python. It asks the user questions using the command:
some_input = input('Answer the question:', ...)
How would I test a function containing a call to input using pytest?
I wouldn't want to force a tester to input text many many times only to finish one test run.
As The Compiler suggested, pytest has a new monkeypatch fixture for this. A monkeypatch object can alter an attribute in a class or a value in a dictionary, and then restore its original value at the end of the test.
In this case, the built-in input function is a value of python's __builtins__ dictionary, so we can alter it like so:
def test_something_that_involves_user_input(monkeypatch):
# monkeypatch the "input" function, so that it returns "Mark".
# This simulates the user entering "Mark" in the terminal:
monkeypatch.setattr('builtins.input', lambda _: "Mark")
# go about using input() like you normally would:
i = input("What is your name?")
assert i == "Mark"
You should probably mock the built-in input function, you can use the teardown functionality provided by pytest to revert back to the original input function after each test.
import module # The module which contains the call to input
class TestClass:
def test_function_1(self):
# Override the Python built-in input method
module.input = lambda: 'some_input'
# Call the function you would like to test (which uses input)
output = module.function()
assert output == 'expected_output'
def test_function_2(self):
module.input = lambda: 'some_other_input'
output = module.function()
assert output == 'another_expected_output'
def teardown_method(self, method):
# This method is being called after each test case, and it will revert input back to original function
module.input = input
A more elegant solution would be to use the mock module together with a with statement. This way you don't need to use teardown and the patched method will only live within the with scope.
import mock
import module
def test_function():
with mock.patch.object(__builtins__, 'input', lambda: 'some_input'):
assert module.function() == 'expected_output'
You can replace sys.stdin with some custom Text IO, like input from a file or an in-memory StringIO buffer:
import sys
class Test:
def test_function(self):
sys.stdin = open("preprogrammed_inputs.txt")
module.call_function()
def setup_method(self):
self.orig_stdin = sys.stdin
def teardown_method(self):
sys.stdin = self.orig_stdin
this is more robust than only patching input(), as that won't be sufficient if the module uses any other methods of consuming text from stdin.
This can also be done quite elegantly with a custom context manager
import sys
from contextlib import contextmanager
#contextmanager
def replace_stdin(target):
orig = sys.stdin
sys.stdin = target
yield
sys.stdin = orig
And then just use it like this for example:
with replace_stdin(StringIO("some preprogrammed input")):
module.call_function()
This can be done with mock.patch and with blocks in python3.
import pytest
import mock
import builtins
"""
The function to test (would usually be loaded
from a module outside this file).
"""
def user_prompt():
ans = input('Enter a number: ')
try:
float(ans)
except:
import sys
sys.exit('NaN')
return 'Your number is {}'.format(ans)
"""
This test will mock input of '19'
"""
def test_user_prompt_ok():
with mock.patch.object(builtins, 'input', lambda _: '19'):
assert user_prompt() == 'Your number is 19'
The line to note is mock.patch.object(builtins, 'input', lambda _: '19'):, which overrides the input with the lambda function. Our lambda function takes in a throw-away variable _ because input takes in an argument.
Here's how you could test the fail case, where user_input calls sys.exit. The trick here is to get pytest to look for that exception with pytest.raises(SystemExit).
"""
This test will mock input of 'nineteen'
"""
def test_user_prompt_exit():
with mock.patch.object(builtins, 'input', lambda _: 'nineteen'):
with pytest.raises(SystemExit):
user_prompt()
You should be able to get this test running by copy and pasting the above code into a file tests/test_.py and running pytest from the parent dir.
Since I need the input() call to pause and check my hardware status LEDs, I had to deal with the situation without mocking. I used the -s flag.
python -m pytest -s test_LEDs.py
The -s flag essentially means: shortcut for --capture=no.
You can do it with mock.patch as follows.
First, in your code, create a dummy function for the calls to input:
def __get_input(text):
return input(text)
In your test functions:
import my_module
from mock import patch
#patch('my_module.__get_input', return_value='y')
def test_what_happens_when_answering_yes(self, mock):
"""
Test what happens when user input is 'y'
"""
# whatever your test function does
For example if you have a loop checking that the only valid answers are in ['y', 'Y', 'n', 'N'] you can test that nothing happens when entering a different value instead.
In this case we assume a SystemExit is raised when answering 'N':
#patch('my_module.__get_input')
def test_invalid_answer_remains_in_loop(self, mock):
"""
Test nothing's broken when answer is not ['Y', 'y', 'N', 'n']
"""
with self.assertRaises(SystemExit):
mock.side_effect = ['k', 'l', 'yeah', 'N']
# call to our function asking for input
I don't have enough points to comment, but this answer: https://stackoverflow.com/a/55033710/10420225
doesn't work if you just copy/pasta.
Part One
For Python3, import mock doesn't work.
You need import unittest.mock and call it as unittest.mock.patch.object(), or from unittest import mock mock.patch.object()...
If using Python3.3+ the above should "just work". If using Python3.3- you need to pip install mock. See this answer for more info: https://stackoverflow.com/a/11501626/10420225
Part Two
Also, if you want to make this example more realistic, i.e. importing the function from outside the file and using it, there's more assembly required.
This is general directory structure we'll use
root/
src/prompt_user.py
tests/test_prompt_user.py
If function in external file
# /root/src/prompt_user.py
def user_prompt():
ans = input("Enter a number: ")
try:
float(ans)
except:
import sys
sys.exit("NaN")
return "Your number is {}".format(ans)
# /root/tests/test_prompt_user.py
import pytest
from unittest import mock
import builtins
from prompt_user import user_prompt
def test_user_prompt_ok():
with mock.patch.object(builtins, "input", lambda _: "19"):
assert user_prompt() == "Your number is 19"
If function in a class in external file
# /root/src/prompt_user.py
class Prompt:
def user_prompt(self):
ans = input("Enter a number: ")
try:
float(ans)
except:
import sys
sys.exit("NaN")
return "Your number is {}".format(ans)
# /root/tests/test_prompt_user.py
import pytest
from unittest import mock
import builtins
from mocking_test import Prompt
def test_user_prompt_ok():
with mock.patch.object(builtins, "input", lambda _: "19"):
assert Prompt.user_prompt(Prompt) == "Your number is 19"
Hopefully this helps people a bit more. I find these very simple examples almost useless because it leaves a lot out for real world use cases.
Edit: If you run into pytest import issues when running from external files, I would recommend looking over this answer: PATH issue with pytest 'ImportError: No module named YadaYadaYada'
A different alternative that does not require using a lambda function and provides more control during the tests is to use the mock decorator from the standard unittest module.
It also has the additional advantage of patching just where the object (i.e. input) is looked up, which is the recommended strategy.
# path/to/test/module.py
def my_func():
some_input = input('Answer the question:')
return some_input
# tests/my_tests.py
from unittest import mock
from path.to.test.module import my_func
#mock.patch("path.to.test.module.input")
def test_something_that_involves_user_input(mock_input):
mock_input.return_value = "This is my answer!"
assert my_func() == "This is my answer!"
mock_input.assert_called_once() # Optionally check one and only one call
The simplest way that works without mocking and easily in doctest for lightweight testing, is just making the input_function a parameter to your function and passing in this FakeInput class with the appropriate list of inputs that you want:
class FakeInput:
def __init__(self, input):
self.input = input
self.index = 0
def __call__(self):
line = self.input[self.index % len(self.input)]
self.index += 1
return line
Here is an example usage to test some functions using the input function:
import doctest
class FakeInput:
def __init__(self, input):
self.input = input
self.index = 0
def __call__(self):
line = self.input[self.index % len(self.input)]
self.index += 1
return line
def add_one_to_input(input_func=input):
"""
>>> add_one_to_input(FakeInput(['1']))
2
"""
return int(input_func()) + 1
def add_inputs(input_func=input):
"""
>>> add_inputs(FakeInput(['1', '5']))
6
"""
return int(input_func()) + int(input_func())
def return_ten_inputs(input_func=input):
"""
>>> return_ten_inputs(FakeInput(['1', '5', '7']))
[1, 5, 7, 1, 5, 7, 1, 5, 7, 1]
"""
return [int(input_func()) for _ in range(10)]
def print_4_inputs(input_func=input):
"""
>>> print_4_inputs(FakeInput(['1', '5', '7']))
1
5
7
1
"""
for i in range(4):
print(input_func())
if __name__ == '__main__':
doctest.testmod()
This also makes your functions more general so you can easily change them to take input from a file rather than the keyboard.
You can also use environment variables in your test code. For example if you want to give path as argument you can read env variable and set default value if it's missing.
import os
...
input = os.getenv('INPUT', default='inputDefault/')
Then start with default argument
pytest ./mytest.py
or with custom argument
INPUT=newInput/ pytest ./mytest.py

Categories

Resources