How to test Python function which writes to file

python, unit-testing

Solution

Call the `write_file` function and check whether `testfile` is created with expected content.

def test_write_file(self):
    a = [1,2,3]
    write_file(a)
    with open('testfile') as f:
        assert f.read() == '123' # Replace this line with the method
                                 #   provided by your testing framework.

If you don't want test case write to actual filesystem, use something like `mock.mock_open`.

Problem

I have a Python function that takes a list as an argument and writes it to a file: ``` def write_file(a): try: f = open('testfile', 'w') for i in a: f.write(str(i)) finally: f.close() ``` How do I test this function ? ``` def test_write_file(self): a = [1,2,3] #what next ? ```

Original source

Related problems