Claudiu Creanga
Claudiu Creanga

Reputation: 8366

In pytest, how to mock method to return the value that you want

I'm unsure how to mock method1 to return what I want in method_to_test (from the data variable)

class A:
  def method1(self):
    return [5,6] # I want to return [3,4] in test

  def method_to_test(self, df):
    colors = self.method1() # Should return [3,4]
    df["name"] = colors
    return df

data = (
  (
     # Input
    {
      "df": pd.Dataframe([random values]),
      "colors": [3,4]
    },
     # Expected
    pd.Dataframe([random values])
  ),
)

@pytest.mark.parametrize('test_input, expected', data)
def test_method(test_input, expected):
  plot = A()
  plot.method1 = test_input["colors"] # doesn't work
  actual = plot.method_to_test(test_input["df"])
  assert_frame_equal(actual, expected)

Here I get object is not callable. I've seen patch decorators but I believe there is a simpler way of doing it...

Upvotes: 0

Views: 698

Answers (1)

phd
phd

Reputation: 94397

Python expects method1 to be a callable — a function, a method, etc. Make it a callable that accepts self and returns the desired value. Let's do it with lambda:

plot.method1 = lambda s: test_input["colors"]

Or create a function:

def mock_method1(self):
    return test_input["colors"]

plot.method1 = mock_method1

Upvotes: 1

Related Questions