Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading