-2

I am trying to mock a readlines() object in python unit tests. What I have so far is

class Sample:
    def read_file(filename):
        with open(filename, "r") as f:
            lines = f.readlines()

I want to write a unit test for readlines() object. So far, I have come up with the following.

TEST_DATA = "test\ntest2\n"
@mock.patch("builtins.open")
def test_open(mock_open):
    mock_open.side_effect = [mock_open(read_data=TEST_DATA).return_value]
    assert mock_open.side_effect == Sample.read_file()

My question here is, how do I assert the returned value of mock_open is the same as the returned value of the actual read_file function in the Sample class? This is where I am failing and not able to go any further. Any help on this is much appreciated! Thank you in advance!

Gingerbread
  • 1,938
  • 8
  • 22
  • 36

1 Answers1

1

In unittest.mock docs there is an example that may help you

Here is the docs example adapted to your code.

from unittest.mock import patch


class Sample:
    def read_file(filename):
        with open(filename, "r") as f:
            lines = f.readlines()
        return lines

TEST_DATA = "test\ntest2\n"
def test_open(mock_open):
    with patch('__main__.open', mock_open(read_data=TEST_DATA)) as m:
        s = Sample()
        res = s.read_file('foo')

    assert res == TEST_DATA
Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43