r/pythonhelp • • Dec 29 '21

Simulate Opening File Inside Script

I want to be able to simulate opening a file inside a script. This avoids me from creating a physical file. I have this:

import io

fake_file = io.StringIO('''
0 2021-12-21
1 2021-12-20
2 2021-12-19
3 2021-12-18
''')

def get_final_line(filename):
    with open(fake_file) as f:
        lines = [i for i in f.read().strip().split('\n')]
        return lines[-1]

get_final_line('/tmp/test.txt')

Originally, I had a physical "/tmp/test.txt", but I am trying to avoid this. So, I saw io.StringIO and according to this, it seems like io.StringIO returns a file-like object? So, I thought it might be possible, when I run this, I get this error:

TypeError: expected str, bytes or os.PathLike object, not StringIO

Anyway, what I want is to define a fake_file variable that represents the content of the file, then, later on, have the open function read the fake file as if it is reading a real file. Is this possible?

3 Upvotes

7 comments sorted by

View all comments

1

u/Goobyalus Dec 29 '21 edited Dec 29 '21

open accepts the location of something to open, so you would have to mock out the open function itself.

You could do something like this:

from unittest.mock import patch, mock_open


def get_final_line(filename):
    with open(filename) as f:
        lines = [i for i in f.read().strip().split('\n')]
        return lines[-1]


def test_get_final_line():
    fake_file = '''
    0 2021-12-21
    1 2021-12-20
    2 2021-12-19
    3 2021-12-18
    '''
    filename = '/tmp/test.txt'
    expected_result = "3 2021-12-18"
    m = mock_open(read_data=fake_file)
    with patch("builtins.open", m):
        result = get_final_line(filename)
    print("result =", result)
    m.assert_called_once_with(filename)
    assert result == expected_result, f"result is '{result}' instead of '{expected_result}'"


if __name__ == "__main__":
    test_get_final_line()

Output:

result =     3 2021-12-18
Traceback (most recent call last):
  File "C:\Users\Optimus Prime\PycharmProjects\RedditQs\kolinkorr839.py", line 39, in <module>
    test_get_final_line()
  File "C:\Users\Optimus Prime\PycharmProjects\RedditQs\kolinkorr839.py", line 35, in test_get_final_line
    assert result == expected_result, f"result is '{result}' instead of '{expected_result}'"
AssertionError: result is '    3 2021-12-18' instead of '3 2021-12-18'

Edit: the error is because I accidentally put indentation in the block string, but it illustrates what's happening better lol.

2

u/kolinkorr839 Dec 29 '21

Thanks, I misunderstood what io.StringIO was supposed to be then.

1

u/Goobyalus Dec 30 '21

Idk, you correctly call it a file-like object.

A StringIO object is analagous to what open returns, i.e. the f in with open('myfile') as f.

So if you're ok with changing the function, you could just do

def get_final_line(filename):
    #with open(fake_file) as f:
    f = fake_file
    # The following 2 lines were unindented because we commented out the with
    lines = [i for i in f.read().strip().split('\n')]
    return lines[-1]

2

u/[deleted] Dec 31 '21

I usually replace open with StringIO

with StringIO(filename) as f:

where filename references a multiline string object.

1

u/Goobyalus Dec 31 '21

Huh, I thought I tried this and it didn't work, but I guess I messed it up. Thanks!

u/kolinkorr839 This is much better!

2

u/kolinkorr839 Dec 31 '21

Thank you! This is much more in line with what I wanted.

1

u/kolinkorr839 Dec 30 '21

Thanks, this is good then.