5.1. Unittest Stub

stub

simple object which always returns the same result

You can also use Stub (a function with fixed value) to simulate input():

>>> def input(_):
...     return 'Mark Watney'
>>>
>>>
>>> input('What is your name?: ')
'Mark Watney'

At the end of the chapter about Functions, there is a mention about lambda expression. This could be also used here to make the code more compact.

>>> input = lambda _: 'Mark Watney'
>>>
>>>
>>> input('What is your name?: ')
'Mark Watney'

Both methods: Function Stub and Lambda Stub works the same.

5.1.1. Case Study A

  • Defining variable with the same name as in outer scope

  • Stub

Shadowing of a global scope is used frequently in Mocks and Stubs. This way, we can simulate user input. Note that Mocks and Stubs will stay until the end of a program.

>>> def input(prompt):
...     return 'Mark Watney'

If we call function input(), it will not ask the user to provide information, but will execute our "overwritten" function (stub), which returns always the same value: 'Mark Watney'.

>>> name = input('Type your name: ')
>>> name
'Mark Watney'

However, there is a problem. If you try to call this function once again, this time expecting different result, it will return the same value once again. This is the nature of stubs.

>>> age = input('Type your age: ')
>>> age
'Mark Watney'

To get different result for each call, you have to use mock, which will be introduced below.

To restore default behavior of input() function use:

>>> from builtins import input