Writing a pytest function to check output in a file in python?

I asked this question about how to write pytest to check the output in stdout and got a solution. Now I need to write a test case to check if the contents are written to the file and that the contents are written as expected for example:

 def writetoafile(): file = open("output.txt",w) file.write("hello\n") file.write("world\n") file.close() 

now a pytest function to check if this is written:

 def test_writeToFile(): file = open("ouput.txt",'r') expected = "hello\nworld\n" assert expected==file.read() 

although this seems to work, I don't think it is perfect, especially hard coding. How is this type of test functions written to a file usually written?

+11
function python file-io pytest
source share
2 answers

There is tmpdir fixture that will create you a temporary directory for each test. Thus, the test will 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 are refactoring the code so that it is not hard-coded, which is a prime example of how testing your code makes you better design it.

+15
source share

Suppose you have this β€œamazing” piece of software in a file called main.py :

 """ main.py """ def write_to_file(text): with open("output.txt", "w") as h: h.write(text) if __name__ == "__main__": write_to_file("Every great dream begins with a dreamer.") 

To test the write_to_file method, you can write something like this to a file in the same folder as test_main.py :

 """ test_main.py """ from unittest.mock import patch, mock_open import main def test_do_stuff_with_file(): open_mock = mock_open() with patch("main.open", open_mock, create=True): main.write_to_file("test-data") open_mock.assert_called_with("output.txt", "w") open_mock.return_value.write.assert_called_once_with("test-data") 

I always try to avoid writing files to disk, even if it is a temporary folder intended for my tests: without touching the disk, your tests are significantly accelerated, especially if you interact a lot with files in your code.

0
source share

All Articles