TypeError: test_custom_function.<locals>.<lambda>() missing 1 required positional argument: '_'

Viewed 28

Having a Python functions as below:

def get_student_id():
    while True:
        try:
            print("ENTER STUDENT ID: ")
            identity = int(input())
            if identity > 0:
                return identity
            else:
                print("That's not a natural number. Try again: ")
        except ValueError:
            print("That's not an integer. Try again: ")

and

def test_get_student_id():
    with mock.patch.object(builtins, 'input', lambda _: '19'):
        assert get_student_id() == '19'

Run pytest command to receive an error: TypeError: test_GetStudentId..() missing 1 required positional argument: '_'

Please help to fix above error. Thanks.

1 Answers

When calling input you're passing no arguments (input()), but you're telling unittest.mock that it has one (lambda _:).
You need to be consistent. Either:

  1. Pass one argument when calling it

    identity = int(input("ENTER STUDENT ID: ")
    
  2. Instruct unittest.mock that function is called with no arguments

    mock.patch.object(builtins, 'input', lambda: '19')
    

From my PoV, the former makes more sense, as you could also get rid of the print statement before.

Related