4

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 ?
Mark van Lent
  • 12,641
  • 4
  • 30
  • 52
user3057314
  • 65
  • 1
  • 7

2 Answers2

5

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.

falsetru
  • 357,413
  • 63
  • 732
  • 636
0

First solution: rewrite you function to accept a writable file-like object. You can then pass a StringIO instead and test the StringIO's value after the call.

Second solution: use some mock library that let you patch builtins.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118