pythontestingpyfakefs

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


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 (\r\n to \n) in text mode, running on linux?


Solution

  • 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 content\n with newlines\n')
            ...
    
    

    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:\foo\bar" == os.path.join('C:\\', 'foo', 'bar'))
        assert os.path.splitdrive(r"C:\foo\bar") == ("C:", r"\foo\bar")
        assert os.path.ismount("C:")
    

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