Input / Output Tests

This is an example of how you can mock input values and test the output stream of student code.

The student must use the input() function to prompt the user for their first name, the again for their last name. Then, print Hello, firstname lastname! including the person's first and last name.

Sample Run:

What is your first name? Jane
What is your last name? Doe
Hello, Jane Doe!

It assumes the student's file name is example.py. Replace the import with whatever you student's file name is.

Note: This code converts the output to all lowercase and removes spaces to compare against the correct value.

Grading Tests:

import unittest
import sys, io
import importlib

stdout = sys.stdout
stdin = sys.stdin
student_code = ""

class CodingRoomsUnitTests(unittest.TestCase):

    def setUp(self):
        global stdout
        global stdin
        stdout = sys.stdout
        stdin = sys.stdin

    def tearDown(self):
        global stdout
        global stdin
        sys.stdin = stdin
        sys.stdout = stdout

    def test_case_1(self):
        global student_code
        sys.stdout = io.StringIO()
        sys.stdin = io.StringIO("Jane\nDoe")

        student_code = importlib.import_module('example')

        output = sys.stdout.getvalue().strip("\n")
        
        self.assertTrue(output.casefold().replace(" ", "").endswith("Hello, Jane Doe!".casefold().replace(" ", "")))

    def test_case_2(self):
        global student_code
        sys.stdout = io.StringIO()
        sys.stdin = io.StringIO("Joe\nMazzone")

        importlib.reload(student_code)

        output = sys.stdout.getvalue().strip("\n")
        
        self.assertTrue(output.casefold().replace(" ", "").endswith("Hello, Joe Mazzone!".casefold().replace(" ", "")))

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

The io.StringIO() for stdin replaces the programs input stream. Each input must be separated by a newline character - \n.

You will also notice that the assertion doesn't compare the output directly with what is expected. Instead it sees if the output stream .endswith() the expected output. This is because the input() function's prompt is included in the output stream, so we only want to check the last thing printed. If you want to include the prompts to ensure students properly included them, you can use assertEqual() and and compare the entire output stream

Sample Solution:

example.py
fname = input("What is your first name?")
lname = input("What is your last name?")

print("Hello, " + fname + " " + lname + "!")

Last updated