Nov-06-2018, 11:43 AM
In test_die(), mock.patch() isn't being used in your with statements. When using "with", you need to assign the operation as a variable and reference that variable in the following code body. From the documentation:
The third problem I see is that rolldie.run() isn't supportive of testing because of the input() calls. In fact, that's likely why it's freezing; rolldie.run() isn't receiving the inputs it wants so the program cannot move forward. Unit tests are best used with functions that return a value. I rewrote the code to support unit testing though there isn't really enough there to test:
with patch('__main__.Class') as MockClass: instance = MockClass.return_value instance.method.return_value = 'foo' assert Class() is instance assert Class().method() == 'foo'In test_die on line 8, there will be an assertion error because rolldie.run() does not return a range object. Your next two assertions would work because those strings are returned by rolldie.run(). A proper test passes a known value to a function/method and validates that the returned value matches expectations.
The third problem I see is that rolldie.run() isn't supportive of testing because of the input() calls. In fact, that's likely why it's freezing; rolldie.run() isn't receiving the inputs it wants so the program cannot move forward. Unit tests are best used with functions that return a value. I rewrote the code to support unit testing though there isn't really enough there to test:
from random import randint def run(): while True: num = integer_input("Enter an number to roll: ") if validate(num): return "Game terminated" roll = randint(1,6) print(format_result(roll)) def integer_input(message): while True: try: x = int(input(message)) return x except ValueError: print("\nInvalid value, please enter an integer.") def validate(num): return num == 0 def format_result(num): return f"Result {num}"With that code, you could test both validate() and format_result() because they have predictable outputs with known inputs. So, you could ensure that validate returns True if a 0 is passed in or that "Result 5" is returned by format_result is a 5 is provided. However, we already know those would work since those functions merely do basic behaviors of Python.