erip erip - 5 months ago 22
Python Question

Why is my assertion failing when reading a NamedTemporaryFile?

I'm writing code that reads a file and creates a dictionary based on the contents of that file. The code is quite straightforward, but I'd like to test the edge cases.

Here's my attempt:

from tempfile import NamedTemporaryFile
from nose.tools import *

def read_file(filename):
with open(filename) as f:
my_dict = { line.strip().split(',')[0] : line.strip().split(',')[1] for line in f }
return my_dict

def test_read_file():
file_contents = b"""Hello,World"""
with NamedTemporaryFile() as fp:
fp.write(file_contents)
my_dict = read_file(fp.name)
print(my_dict)
assert my_dict == { "Hello" : "World" }


Unfortunately this assertion fails because
my_dict
is an empty dictionary.

My understanding is that once a
NamedTemporaryFile
is closed, it is destroyed, so I don't expect it to be destroyed until directly after
read_file
's
my_dict
is populated.
fp
is being opened twice: once to write and once to read -- is this the troublemaker?

Is this the right way to test a function that reads a file? If so, why is my assertion failing? If not, what's a better mechanism for writing this test?

Answer

You need to flush the write to ensure the data is written before reading.

def test_read_file():
    file_contents = b"""Hello,World"""
    with NamedTemporaryFile() as fp:
        fp.write(file_contents)
        fp.flush()
        my_dict = read_file(fp.name)
    print(my_dict)
    assert my_dict == { "Hello" : "World" }