TH58PZ700U
TH58PZ700U

Reputation: 43

Patching local class reference

Like many people, I'm having issues with mock patching and getting the path right. Specifically, my code references another class in the same file and I'm having trouble patching that reference.

I have the following python file, package/engine/dataflows/flow.py:

class Flow:

  def run(self, type):
    if type == 'A':
      method1()
    elif type == 'B':
      method2()
    else:
      backfill = Backfill()
      backfill.run()


class Backfill(Flow):

  def run(self):
    ...

And a test file package/tests/engine/dataflows/test_Flow.py

import unittest
from unittest.mock import Mock, patch
from engine.dataflows.flow import Flow

class MockFlow(Flow):
  ...

class TestFlowRun(unittest.TestCase):

  def setUp(self):
    self.flow = MockFlow()

  def test_run_type_c(self):
    with patch('engine.dataflows.flow.Backfill') as mock_backfill:
      self.flow.run(type='C')
      assert mock_backfill.run.call_count == 1

The patch works in that it doesn't throw an error when run with pytest, but the assertion is failing. I assume that is because the local reference to the Backfill class has essentially already been imported when MockFlow was initialized, but I have been unable to come up with a patching path that handles this.

The contents of flow.py include the Flow base class and a couple of child classes that implement different data flow patterns. They're co-located in the same file for ease of understanding and common dependencies.

Upvotes: 1

Views: 379

Answers (1)

Matthew Best
Matthew Best

Reputation: 26

The problem is that you are checking the run() function of a class, not an instantiation of that class. The mocked Backfill class will return an instance of the class via its constructor/init. That is the mock / object you will want to check.

with patch('engine.dataflows.flow.Backfill') as mock_backfill:
    mocked_backfill_instance = mock_backfill.return_value
    self.flow.run(type='C')
    assert mocked_backfill_instance.run.call_count == 1

Upvotes: 1

Related Questions