Is it possible to mock the platform for reading and writing files in binary and text mode?

Question:

I would to test if a system reads and writes files correctly (text mode / binary mode) on multiple platforms, at least on linux and windows. (Using pytest).

See https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

It is possible to mock a filesystem with pyfakefs, for example.
But I have not been able to find a mock for simulating the windows behaviour with files opened in text mode, when running the tests on linux.

Is it possible to force the translation of eol (rn to n) in text mode, running on linux?

Asked By: sunew

||

Answers:

Just stumbled over this – while this is an old question, maybe the answer will help someone else…
In pyfakefs, you can change your fake file system, e.g. (example in pytest):

    def test_windows_stuff_under_linux(fs):
        fs.is_windows_fs = True
        file_path = 'C:/foo/bar/baz'
        with open(file_path, 'w') as f:
            f.write('Some contentn with newlinesn')
        ...

In current pyfakefs versions, there is a more comprehensive method to change the fake OS – you can set os instead of is_windows_fs. This changes a few more properties (like the path delimiter and the case sensitivity) to match the selected OS. Here is an example from the documentation, which shall also run under Linux:

from pyfakefs.fake_filesystem import OSType

def test_windows_paths(fs):
    fs.os = OSType.WINDOWS
    assert r"C:foobar" == os.path.join('C:\', 'foo', 'bar'))
    assert os.path.splitdrive(r"C:foobar") == ("C:", r"foobar")
    assert os.path.ismount("C:")

OSType is an enum with the possible values OSType.WINDOWS, OSType.LINUX and OSType.MACOS.

Answered By: MrBean Bremen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.