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:
1
What is your first name? Jane
2
What is your last name? Doe
3
Hello, Jane Doe!
Copied!
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:

1
import unittest
2
import sys, io
3
import importlib
4
​
5
stdout = sys.stdout
6
stdin = sys.stdin
7
student_code = ""
8
​
9
class CodingRoomsUnitTests(unittest.TestCase):
10
​
11
def setUp(self):
12
global stdout
13
global stdin
14
stdout = sys.stdout
15
stdin = sys.stdin
16
​
17
def tearDown(self):
18
global stdout
19
global stdin
20
sys.stdin = stdin
21
sys.stdout = stdout
22
​
23
def test_case_1(self):
24
global student_code
25
sys.stdout = io.StringIO()
26
sys.stdin = io.StringIO("Jane\nDoe")
27
​
28
student_code = importlib.import_module('example')
29
​
30
output = sys.stdout.getvalue().strip("\n")
31
32
self.assertTrue(output.casefold().replace(" ", "").endswith("Hello, Jane Doe!".casefold().replace(" ", "")))
33
​
34
def test_case_2(self):
35
global student_code
36
sys.stdout = io.StringIO()
37
sys.stdin = io.StringIO("Joe\nMazzone")
38
​
39
importlib.reload(student_code)
40
​
41
output = sys.stdout.getvalue().strip("\n")
42
43
self.assertTrue(output.casefold().replace(" ", "").endswith("Hello, Joe Mazzone!".casefold().replace(" ", "")))
44
​
45
if __name__ == '__main__':
46
unittest.main()
Copied!
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
1
fname = input("What is your first name?")
2
lname = input("What is your last name?")
3
​
4
print("Hello, " + fname + " " + lname + "!")
Copied!
Last modified 2mo ago
Export as PDF
Copy link