3
\$\begingroup\$

I implemented a test that reads data from temp file on Windows.
I originally had an issue that I solved with the help of this answer

def test_read(self):
    """Test read from file"""
    import tempfile
    import os
    try:
        with tempfile.NamedTemporaryFile(delete=False) as temp:
            content = 'Some data'
            temp.write(content.encode('utf-8'))
            temp.flush()
            self.assertEqual(content, b.read(Path(temp.name)))
    finally:
        os.remove(temp.name)

How can I do this better?
Is it ok to have try...finally in the test?

b is a custom module. It reads data from temp file.

def read(path):
    """Reads file content from FS"""
    if path in VIRTUAL_FS:
       return VIRTUAL_FS[path]
    with open(path.as_posix(), 'r') as file:
       return file.read()
\$\endgroup\$
  • \$\begingroup\$ What is b? What is the purpose of this test? \$\endgroup\$ – 200_success Sep 15 '14 at 15:43
  • \$\begingroup\$ Purpose that b reads data from file properly. \$\endgroup\$ – drets Sep 15 '14 at 15:59
2
\$\begingroup\$

In the try block, temp might not get assigned, so temp.name would be an error. But this is an extremely unlikely scenario.

You seem to be going out of your way to defeat the natural clean-up capability of the named temporary file:

If delete is true (the default), the file is deleted as soon as it is closed.

Since the file is opened via a with block, it should be closed automatically at the end of the block, and automatically deleted as well, if you let it. Therefore, you shouldn't need the try...finally at all, and you can remove the delete=False parameter from NamedTemporaryFile:

def test_read(self):
    """Test read from file"""
    import tempfile

    with tempfile.NamedTemporaryFile() as temp:
        content = 'Some data'
        temp.write(content.encode('utf-8'))
        temp.flush()
        self.assertEqual(content, b.read(Path(temp.name)))

When you open a file for reading, you can omit the r in here:

with open(path.as_posix(), 'r') as file:
   return file.read()

Finally, b is terrible name. It doesn't tell anything about the module.

\$\endgroup\$
  • 1
    \$\begingroup\$ Thanks, it's good to know the default mode for open function. On the other hand if I would remove the delete=False and run it on Windows, I get permission denied IOError as in this question. \$\endgroup\$ – drets Sep 15 '14 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.