'Python patch returning magicmock instead of return value

I have this code

import cv2
from src.utilities.binary import message2binary
from src.utilities.stegUtils import verify_payload
def encode(input_path: any, payload: str, output_path: str, terminator: str = "#####") -> None:
  img = cv2.imread(input_path)
  verify_payload(payload, img)
  
  BINARY_DATA = message2binary(payload)
  LOGGER.debug(f"Binary payload: {BINARY_DATA}")
  
  # Append terminator and convert payload to list
  payload_finalized = list(message2binary(payload + terminator))
  for line in img:
      for pixel in line:
          bit_encoded = message2binary(pixel)
          for component in list(RGB):
            if not payload_finalized:
              cv2.imwrite(output_path, img)
              return LOGGER.info(f"Saved as {output_path}")
            bit = payload_finalized.pop(0)
            pixel[component.value] = int(
              bit_encoded[component.value][:-1] + bit,
              2)

When I try to patch it in unittest like this I come to error that imread returns magicMock instead of return value I gave it

  @patch("src.convert.cv2.imread")
  @patch("src.convert.verify_payload", autospec=True)
  def test_should_encrypt_message(self, mock_imread: MagicMock, mock_verify_payload: Mock):
    """Should encrypt message"""
    # Given
    input_path = "intput_path"
    payload = "a"
    output_path = "output_path"
    img = np.array([
      [ 
       # R, G, B  |  R, G, B | R, G, B  | R, G, B   
        [1, 0, 1], [1, 0, 0], [0, 0, 1], [1, 1, 0], 
      ] * 255
    ])
    mock_imread.return_value = img
    # When
    encode(input_path, payload, output_path)
    # Then
    mock_imread.assert_called_once_with(input_path)
    mock_verify_payload.assert_called_once(payload, img)

Can someone explain why is this happening?



Solution 1:[1]

Solved this by changing order of anotations to

  @patch("src.convert.verify_payload", autospec=True)
  @patch("src.convert.cv2.imread")
  def test_should_encrypt_message(self, mock_imread: MagicMock, mock_verify_payload: Mock):

Weird thing but ok ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Karafra