Created
January 26, 2018 04:43
-
-
Save acbart/a2fca7dbc5ee4dd627abf6be5128fd08 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
Created on Thu Jan 25 23:27:40 2018 | |
@author: acbart | |
""" | |
import unittest | |
from unittest.mock import patch | |
import io | |
import sys | |
import importlib | |
def make_inputs(*input_list): | |
''' | |
Helper function for creating mock user input. | |
Params: | |
input_list (list of str): The list of inputs to be returned | |
Returns: | |
function (str=>str): The mock input function that is returned, which | |
will return the next element of input_list each | |
time it is called. | |
''' | |
generator = iter(input_list) | |
def mock_input(prompt=''): | |
print(prompt) | |
return next(generator) | |
return mock_input | |
class TextExternal(unittest.TestCase): | |
maxDiff = None | |
def run_student(self): | |
''' | |
Run the students' code; if it has been run before, then we reload | |
it instead. | |
''' | |
if 'student' not in sys.modules: | |
import student | |
else: | |
importlib.reload(sys.modules['student']) | |
def test_student(self): | |
for name in ["AustinCorgiBart", "jrhead"]: | |
prompter = make_inputs(name) | |
with patch('sys.stdout', new=io.StringIO()) as captured_output: | |
with patch('builtins.input', prompter): | |
try: | |
self.run_student() | |
except StopIteration: | |
msg=("Failed to accept input for name '{}'. " | |
"I typed '{}' but it wasn't accepted." | |
).format(name) | |
self.fail(msg=msg) | |
student_output = captured_output.getvalue() | |
expected = "Welcome!\nGive me your name:\nHiya, "+name+"\n" | |
self.assertEqual(student_output, expected) | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment