Reputation: 407
I tried to word the title as clearly as possible. I'm new to unit testing, and I have a handle on some of the more basic types of assertions, but there is one test I haven't figured out. So I have user enter some type of input and I print the output by calling the variable preceding some type of message. Here is the py file the testsuite is testing
def get_input()
pirateInput = input("What be ye name?! ")
print("Ahoy Captain ", pirateInput)
The user enters a name and I just print it out. So the expected output should be "Ahoy Captain [user input]"
Here is my test suite
import unittest
from unittest.mock import patch
from get_input import *
class GetInputTest(unittest.TestCase):
def test_ValuePrints(self):
#patch input as 'Hook'
@patch('builtins.input', return_value='Hook'
saved_stdout = sys.stdout
try:
out = io.StringIO()
sys.stdout = out
get_input()
output = out.getvalue().strip()
assert output == 'Ahoy Captain Hook'
finally:
sys.stdout = saved_stdout
if __name__ == "__main__":
unittest.main()
So I check for the output I'm expecting, but the test does patch the input as expected. I don't know if I'm clear but hopefully someone can help. If you need more detail please let me know.
Thanks
Upvotes: 1
Views: 1990
Reputation: 10069
The problem is pretty simple. The print
function already adds a space between each pair of arguments, so if you do
print("Ahoy Captain ", pirateInput)
It will print: Ahoy Captain Hook
. Notice the two spaces, the one you add at the end of the first string and the one added by print
. Just remove the one in your string and it will work.
Here's a full working example:
import unittest
import sys
import io
import logging
from unittest.mock import patch
def get_input():
pirateInput = input("What be ye name?! ")
print("Ahoy Captain", pirateInput)
class GetInputTest(unittest.TestCase):
@patch('builtins.input', return_value='Hook')
def test_ValuePrints(self, sth):
log = logging.getLogger( "SomeTest.testSomething" )
saved_stdout = sys.stdout
try:
out = io.StringIO()
sys.stdout = out
get_input()
output = out.getvalue().strip()
log.debug(output)
assert output == 'Ahoy Captain Hook'
finally:
sys.stdout = saved_stdout
if __name__ == "__main__":
logging.basicConfig( stream=sys.stderr )
logging.getLogger( "SomeTest.testSomething" ).setLevel( logging.DEBUG )
unittest.main()
Test run:
$ python3 main.py
DEBUG:SomeTest.testSomething:Ahoy Captain Hook
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Upvotes: 1