writing a pytest function to check outputting to a file in python?

There is the tmpdir fixture which will create you a per-test temporary directory. So a test would look something like this:

def writetoafile(fname):
    with open(fname, 'w') as fp:
        fp.write('Hello\n')

def test_writetofile(tmpdir):
    file = tmpdir.join('output.txt')
    writetoafile(file.strpath)  # or use str(file)
    assert file.read() == 'Hello\n'

Here you’re refactoring the code to not be hardcoded either, which is a prime example of how testing your code makes you design it better.

Leave a Comment