Assertion error in Magic Mock using Pytest in Python

29 views Asked by At

I am trying to write a pytest code for below code:

# file_handler.py

def read_file(file_path):
    try:
        with open(file_path, 'r') as file:
            data = file.read()
            processed_data = data.upper()  # Convert the content to uppercase
        return processed_data
    except FileNotFoundError:
        return None

Below is the pytest code I have written:

# test_file_handler.py

import pytest
from unittest.mock import patch, MagicMock
from file_handler import read_file


@patch('file_handler.open')
def test_file_handler(mock_open):
    mock_response = MagicMock()
    mock_response.processed_data = 'TEST'
    mock_open.return_value = mock_response
    data = read_file('file_path.txt')
    mock_open.assert_called_once_with('file_path.txt', 'r')
    assert data == 'TEST'


if __name__ == "__main__":
    pytest.main()

But I keep getting this error AssertionError: assert <MagicMock name='open().__enter__().read().upper()' id='2690480952400'> == 'TEST'. This is my first time with mocking in pytest.

Here is the full output and error:

============================= test session starts =============================
collecting ... collected 1 item

test_file_handler.py::test_file_handler FAILED                           [100%]
test_file_handler.py:7 (test_file_handler)
<MagicMock name='open().__enter__().read().upper()' id='2690480952400'> != 'TEST'

Expected :'TEST'
Actual   :<MagicMock name='open().__enter__().read().upper()' id='2690480952400'>
<Click to see difference>

mock_open = <MagicMock name='open' id='2690480795408'>

    @patch('file_handler.open')
    def test_file_handler(mock_open):
        mock_response = MagicMock()
        mock_response.processed_data = 'TEST'
        mock_open.return_value = mock_response
        data = read_file('file_path.txt')
        mock_open.assert_called_once_with('file_path.txt', 'r')
>       assert data == 'TEST'
E       AssertionError: assert <MagicMock name='open().__enter__().read().upper()' id='2690480952400'> == 'TEST'

test_file_handler.py:15: AssertionError


============================== 1 failed in 0.04s ==============================
0

There are 0 answers