I've been trying to write a test (using unittest) to test the output of a function. The function is a follows:
def main():
arg_pressent = len(sys.argv)
if arg_pressent < 2:
print "usage: ./pyPeerChat [IP ADDRESS of pc] / [0 (if the network is not known. This will assume that this peer will be the start of a new network)]"
else:
IP = str(sys.argv[1])
connect.main(IP)
if __name__ == '__main__':
main()
So, my test would need test the fact that, when this function runs on its own (not being passed any arguments), it prints 'usage: ./pyPeerChat [IP ADDRESS of pc] / [0 (if the network is not known. This will assume that this peer will be the start of a new network)]'.
So far, the test I've currently been trying to implement has been:
import myModuleChat
from io import StringIO
import unittest
from mock import patch
def main():
Testmain.test_main_prints_without_ARGs()
class TestMain(unittest.TestCase):
def test_main_prints_without_ARGs(self):
expected_print = 'usage: ./pyPeerChat [IP ADDRESS of Bootpeer] / [0 (if the network is not known. This will assume that this peer will be the #start of a new network)]'
with patch('sys.stdout', new=StringIO()) as fake_out:
pyPeerChat.main()
self.assertEqual(fake_out.getvalue(), expected_print)
if __name__ == '__main__':
test_program = unittest.main(verbosity=0, buffer=False, exit=False)
However, I've been unable to get this test to pass sucessfully. The test fails, and I get an error. Below is the entire output of the test, with the error:
======================================================================
ERROR: test_main_prints_without_ARGs (__main__.TestMain)
----------------------------------------------------------------------
Traceback (most recent call last):
File "testpyPeerChat.py", line 24, in test_main_prints_without_ARGs
pyPeerChat.main()
File "/home/peer-node/Testing/P2PChat/source/pyPeerChat.py", line 47, in main
print "usage: ./pyPeerChat [IP ADDRESS of Bootpeer] / [0 (if the network is not known. This will assume that this peer will be the start of a new network)]"
TypeError: unicode argument expected, got 'str'
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
I'm not at all sure what this error means because the code works fine. Is there an easier way to write the test I need, or a way to fix my test?