`
def conversion():
options = print('Would you like to convert hours to mins, or mins to hours?')
choice = input()
if choice == 'hours to mins':
hours = int(input('How many hours? '))
mins = hours * 60
print(mins, 'Minutes')
elif choice == 'mins to hours':
mins = int(input('How many minutes? '))
hours = mins/60
print(hours, 'Hours')
else:
print('An error has occured')
conversion()
This is the production code which is meant to be used to write a corresponding test code. `
I am unsure on how to go about writing a test code using ‘siminput’ ‘assert’ and the a variable ‘actual’ to write a working test code for the line of code above for it to properly run in unittest.
2
Answers
You can use
pytest
with thepytest-mock
extension. Install them via pip or conda, or whatever you use.Quick Fix
First I made a small change to your code to make it a bit easier to test: I added a return statement. Now the code will also return the result.
Ok, now we create a test
when we run this now with
pytest -s
from the command line, we see the expected print result and a green dot for the passed test. Try to add the other scenarios and error cases on your own (e.g. what happens if hour input is not an int)You can also mock the
builtin.print
and check if it was called with the right arguments (mock_print.assert_called_with(3*60, "Minutes")
.See Mocking examples for further details.
Better Solution
As already mentioned it’d be a good idea to separate concerns in your code.
now you can test the "business logic" (the conversion) separately from the User interface…
test_input.py:
test_conversion.py: