1

I have this simple program in Python (hello.py):

name=input()
print("Hello " + name)

As simple as that, no classes, no functions, no nothing, just an input and the corresponding output.

My aim is just to create test_hello.py, a test file for hello.py. I spend a few hours searching on the internet, but I only found unit tests for functions or methods but not for a simple input and output program. Any clue? Thank you a lot in advance!

Note: Stack overflow suggests that there is an answer: How to assert output with nosetest/unittest in python? But the two questions are very different, there aren't functions in my code and there is an input(). In the "answer" suggested the code is inside a function and there is no input().

  • 1
    Is there a specific reason? and how would you check the expected output? It should, for example, return something or write the output to the file. – mad_ Aug 31 '18 at 17:06
  • 2
    Might be better to write a bash script for this – Mitch Aug 31 '18 at 17:08
  • I just don't see how you are going to import or call this to run in your test as it is not function, you would have to code `hello.py` to run in the test code, v a predicted outcome which you could do with a function, but you don't want to use functions, hmm – vash_the_stampede Aug 31 '18 at 23:22

2 Answers2

1

Finally, I came up with the solution:

import unittest
import os
import subprocess

class TestHello(unittest.TestCase):

    def test_case1(self):
        input = "Alan"
        expected_output = "Hello Alan"
        with os.popen("echo '" + input + "' | python hello.py") as o:
            output = o.read()
        output = output.strip() # Remove leading spaces and LFs
        self.assertEqual(output, expected_output)

    def test_case2(self):
        input = "John"
        expected_output = "Hello John"
        with os.popen("echo '" + input + "' | python hello.py") as o:
            output = o.read()
        output = output.strip() # Remove leading spaces and LFs
        self.assertEqual(output, expected_output)

if __name__ == '__main__':
    unittest.main()

I have two test cases: "Alan" must print "Hello Alan" and John must print "Hello John".

Thanks guys for your clues!

0

I really suggest using classes or functions, but if you insisted then you can try to use it in a subprocess and capture the output

this might help

Alex Z
  • 76
  • 3