Search code examples
pythontestingpytestpyfakefs

Pytestfs write then read doesn't return expected value


I'm trying to write a test involving the filesystem. I chose to use pyfakefs and pytest for writing these tests. When I was trying to write and then read from the fake filesystem, I couldn't seem to get any tests to work. So, I wrote a simple test to ensure that pyfakefs was reading the right value:

def test_filesystem(fs):
    with open("fooey.txt", "w+") as my_file:
        my_file.write("Hello")
        read = my_file.read(-1)
        assert os.path.exists("fooey.txt")
        assert "Hello" in read

The first assertion passes. The second one fails. When I debug, read has a value of ''. I'm struggling to understand what's going on here. Does file writing or reading not work within pyfakefs? Am I doing something wrong?


Solution

  • def test_filesystem(fs):
        with open("fooey.txt", "w") as my_file:
            my_file.write("Hello")
            
        with open("fooey.txt", "r") as my_file:
            read = my_file.read()
            assert os.path.exists("hoklh\\fooey.txt")
            assert "Hello" in read
    

    This should do it!