""" Study python3's ``tempfile`` library. """ from __future__ import print_function import os import tempfile import unittest class TestTempFile(unittest.TestCase): """ Test of some futures of the ``tempfile`` standard library module. """ def test_buggy_future_with_wrong_mode_value(self): """ When you give some wrong value to the ``mode`` argument (i.e. ``mode='wr'``) the next error is occurred: ValueError: must have exactly one of create/read/write/append mode Which is a blunder of the particular developer, you need be more careful, but "temporary" file are created on the disk anyway, and now it becomes not so temporary as expected. Because of error, program is interrupted, empty file remains on the disk. Temp file will not be deleted automatically, how it happens whilst normally finish the program without running the ``close()`` method, or when it will be stopped because of any exception. Furthermore, it is occur only with python 3.x versions. :Note: tested on Python 3.4.3 (default, Oct 14 2015, 20:28:29) """ containing_dir = os.path.dirname(os.path.abspath(__file__)) dir_content_before_fail = os.listdir(containing_dir) with self.assertRaises(ValueError): tempfile.NamedTemporaryFile(prefix='eggs_spam_foo_', suffix='.pig', mode='wr', dir=containing_dir) dir_content_after_fail = os.listdir(containing_dir) dir_content_diff = list( set(dir_content_after_fail) - set(dir_content_before_fail) ) smug_git = dir_content_diff.pop() self.addCleanup(os.remove, smug_git) self.assertNotEqual(dir_content_before_fail, dir_content_after_fail) print("Gotcha, smug git! I've knew about you! You shall not pass!" "\n({} was deleted automatically.)".format(smug_git)) if __name__ == '__main__': unittest.main()