Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: TypeError: <lambda>() takes 0 positional arguments but 1 was given due to assert

I am new to making unit tests. I'm currently running pytest. I have this Program.py running but when I run pytest on my Program_test.py I've been failing the tests due to these TypeErrors from my where I had my assert line on the code below. I have the program ask the users for an input value or enter to exit the program. I have the 'import pytest' already included in my Program_test.py program.

Am I using lambda wrong? I'm not sure how to best approach this and get those user inputs to work. This is just testing the get_weight function from users.

***It was already fixed. I had a problem with lambda and underneath was very helpful

like image 358
smokingpenguin Avatar asked Feb 12 '19 01:02

smokingpenguin


1 Answers

Here's an example to show where you are going wrong and for the purpose of explanation I am assigning the lambdas to variables:

zero_arg_lambda = lambda: "131"  # Takes no args
one_arg_lambda = lambda x: "131"  # Takes one arg

Call zero_arg_lambda with arg (same as your error):

zero_arg_lambda(1)
>>> Traceback (most recent call last):
>>> File "<input>", line 1, in <module>
>>> TypeError: <lambda>() takes no arguments (1 given)

Call one_arg_lambda :

one_arg_lambda(1)
>>> "131"

So in short your code is passing a parameter to the lambda even though you have specified that it does not take one.

The one_arg_lambda example takes a parameter and simply returns the value to the right of the colon. I would recommend reading over the docs on lambda

Or if you don't look there the expected lambda format is:

lambda parameters: expression

Also note the docs on monkeypatch.context.setattr which have a good example of using a lambda expression.

To pin-point it the error in your code is coming from the context.setattr call inside your test.

def test_get_weight_returns_valid_input(monkeypatch):
    with monkeypatch.context() as context:
        # Old line causing error: context.setattr('builtins.input', lambda: "131")
        context.setattr('builtins.input', lambda x: "131")  # Fixed 
like image 154
cullzie Avatar answered Sep 17 '22 12:09

cullzie