0

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?

Julia Norman
  • 193
  • 1
  • 11
  • 2
    The file pointer is at the end of the file and so all you can read is an empty string. Jump back to the start with [`seek(0)`](https://docs.python.org/3/library/io.html#io.TextIOBase.seek). – Matthias Jun 01 '23 at 14:43
  • Thank you @Matthias, that was precisely it. I misunderstood what `read(-1)` does: I thought that'd read the whole file regardless of where my position was. – Julia Norman Jun 01 '23 at 14:56

1 Answers1

1
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!

  • Whoa, that's so weird. This does work on my end. Is it something to do with `'w+'` mode? – Julia Norman Jun 01 '23 at 14:48
  • Oh I see - because I need to seek to the beginning. Thank you and @Matthias – Julia Norman Jun 01 '23 at 14:53
  • Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Jun 02 '23 at 00:28