python - Getting started with unit testing for functions without return values -
i've got program that's built on functions taks user inputs inside functions , not parameters before function: example, function
def my_function(): = input("a: ") b = input("b: ") print(a+b)
and understand far unit testing function harder unit test function works example this:
def another_function(a,b): return(a+b)
so how go testing function looks my_function
, example? feels if easy test manually entering incorrect inputs , checking errors, have write test suite tests functions automatically.
given function input comes input
, output goes print
, have "mock" both of these functions test my_function
. example, using simple manual mocking:
def my_function(input=input, print=print): = input("a: ") b = input("b: ") print(a+b) if __name__ == '__main__': inputs = ['hello', 'world'] printed = [] def mock_input(prompt): return inputs.pop(0) def mock_print(text): printed.append(text) my_function(mock_input, mock_print) assert len(inputs) == 0, 'not input used' assert len(printed) == 1, '{} items printed'.format(len(printed)) assert printed[0] == 'helloworld'
when compare to:
assert my_function('hello', 'world') == 'helloworld'
you can see why latter preferred!
you use proper mocking library more neatly, without having supply functions arguments; see e.g. how supply stdin, files , environment variable inputs python unit tests?.
Comments
Post a Comment