pax_global_header00006660000000000000000000000064131701221170014505gustar00rootroot0000000000000052 comment=225bc53df5905a8202e3c6e0b0ab651ac085d1f1 backports.tempfile-1.0/000077500000000000000000000000001317012211700151415ustar00rootroot00000000000000backports.tempfile-1.0/.coveragerc000066400000000000000000000001501317012211700172560ustar00rootroot00000000000000# http://coverage.readthedocs.org/en/latest/config.html [run] branch = True source = src tests backports.tempfile-1.0/.gitignore000066400000000000000000000003051317012211700171270ustar00rootroot00000000000000# Python bytecode *.pyc *.pyo __pycache__ # setuptools-generated *.egg-info/ .eggs/ build/ dist/ # Tox working directory .tox # pytest cache directory .cache/ # Test coverage .coverage htmlcov backports.tempfile-1.0/.travis.yml000066400000000000000000000012321317012211700172500ustar00rootroot00000000000000language: python cache: pip matrix: include: - { python: '2.7', env: TOXENV=py27 } - { python: '3.4', env: TOXENV=py34 } - { python: '3.5', env: TOXENV=py35 } - { python: '3.6', env: TOXENV=py36 } - { python: 'pypy', env: TOXENV=pypy } - { python: 'pypy3', env: TOXENV=pypy3 } # Report coverage for the latest Python 2 and 3 versions. - { python: '2.7', env: TOXENV=py27-codecov } - { python: '3.6', env: TOXENV=py36-codecov } # Avoid overriding the default install step, # so that automatic pip caching works. # # See: https://github.com/travis-ci/travis-ci/issues/3239 # before_script: - pip install tox script: - tox backports.tempfile-1.0/HACKING.rst000066400000000000000000000007221317012211700167400ustar00rootroot00000000000000============================= Working on backports.tempfile ============================= Running the tests ================= Running ``tox``, ``detox``, or ``pytest`` should all work. With ``unittest``:: python -m unittest discover tests Coverage ======== With ``coverage``:: coverage run -m unittest discover tests coverage report coverage html With ``pytest`` and ``pytest-cov``:: py.test --cov py.test --cov --cov-report=html backports.tempfile-1.0/LICENSE000066400000000000000000000307451317012211700161570ustar00rootroot00000000000000A. HISTORY OF THE SOFTWARE ========================== Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands as a successor of a language called ABC. Guido remains Python's principal author, although it includes many contributions from others. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) in Reston, Virginia where he released several versions of the software. In May 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Creations (now Zope Corporation, see http://www.zope.com). In 2001, the Python Software Foundation (PSF, see http://www.python.org/psf/) was formed, a non-profit organization created specifically to own Python-related Intellectual Property. Zope Corporation is a sponsoring member of the PSF. All Python releases are Open Source (see http://www.opensource.org for the Open Source Definition). Historically, most, but not all, Python releases have also been GPL-compatible; the table below summarizes the various releases. Release Derived Year Owner GPL- from compatible? (1) 0.9.0 thru 1.2 1991-1995 CWI yes 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes 1.6 1.5.2 2000 CNRI no 2.0 1.6 2000 BeOpen.com no 1.6.1 1.6 2001 CNRI yes (2) 2.1 2.0+1.6.1 2001 PSF no 2.0.1 2.0+1.6.1 2001 PSF yes 2.1.1 2.1+2.0.1 2001 PSF yes 2.1.2 2.1.1 2002 PSF yes 2.1.3 2.1.2 2002 PSF yes 2.2 and above 2.1.1 2001-now PSF yes Footnotes: (1) GPL-compatible doesn't mean that we're distributing Python under the GPL. All Python licenses, unlike the GPL, let you distribute a modified version without making your changes open source. The GPL-compatible licenses make it possible to combine Python with other software that is released under the GPL; the others don't. (2) According to Richard Stallman, 1.6.1 is not GPL-compatible, because its license has a choice of law clause. According to CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 is "not incompatible" with the GPL. Thanks to the many outside volunteers who have worked under Guido's direction to make these releases possible. B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON =============================================================== PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 -------------------------------------------- 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using this software ("Python") in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python. 4. PSF is making Python available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using Python, Licensee agrees to be bound by the terms and conditions of this License Agreement. BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 ------------------------------------------- BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization ("Licensee") accessing and otherwise using this software in source or binary form and its associated documentation ("the Software"). 2. Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use the Software alone or in any derivative version, provided, however, that the BeOpen Python License is retained in the Software, alone or in any derivative version prepared by Licensee. 3. BeOpen is making the Software available to Licensee on an "AS IS" basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 5. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 6. This License Agreement shall be governed by and interpreted in all respects by the law of the State of California, excluding conflict of law provisions. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between BeOpen and Licensee. This License Agreement does not grant permission to use BeOpen trademarks or trade names in a trademark sense to endorse or promote products or services of Licensee, or any third party. As an exception, the "BeOpen Python" logos available at http://www.pythonlabs.com/logos.html may be used according to the permissions granted on that web page. 7. By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms and conditions of this License Agreement. CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 --------------------------------------- 1. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191 ("CNRI"), and the Individual or Organization ("Licensee") accessing and otherwise using Python 1.6.1 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 1.6.1 alone or in any derivative version, provided, however, that CNRI's License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) 1995-2001 Corporation for National Research Initiatives; All Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version prepared by Licensee. Alternately, in lieu of CNRI's License Agreement, Licensee may substitute the following text (omitting the quotes): "Python 1.6.1 is made available subject to the terms and conditions in CNRI's License Agreement. This Agreement together with Python 1.6.1 may be located on the Internet using the following unique, persistent identifier (known as a handle): 1895.22/1013. This Agreement may also be obtained from a proxy server on the Internet using the following URL: http://hdl.handle.net/1895.22/1013". 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 1.6.1. 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. This License Agreement shall be governed by the federal intellectual property law of the United States, including without limitation the federal copyright law, and, to the extent such U.S. federal law does not apply, by the law of the Commonwealth of Virginia, excluding Virginia's conflict of law provisions. Notwithstanding the foregoing, with regard to derivative works based on Python 1.6.1 that incorporate non-separable material that was previously distributed under the GNU General Public License (GPL), the law of the Commonwealth of Virginia shall govern this License Agreement only as to issues arising under or with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between CNRI and Licensee. This License Agreement does not grant permission to use CNRI trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By clicking on the "ACCEPT" button where indicated, or by copying, installing or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and conditions of this License Agreement. ACCEPT CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 -------------------------------------------------- Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All rights reserved. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. backports.tempfile-1.0/README.rst000066400000000000000000000024521317012211700166330ustar00rootroot00000000000000================== backports.tempfile ================== This package provides backports of new features in Python's tempfile_ module under the backports_ namespace. .. _tempfile: https://docs.python.org/3.6/library/tempfile.html .. _backports: https://pypi.python.org/pypi/backports .. image:: https://img.shields.io/pypi/v/backports.tempfile.svg :target: https://pypi.python.org/pypi/backports.tempfile .. image:: https://img.shields.io/badge/source-GitHub-lightgrey.svg :target: https://github.com/pjdelport/backports.tempfile .. image:: https://img.shields.io/github/issues/pjdelport/backports.tempfile.svg :target: https://github.com/pjdelport/backports.tempfile/issues?q=is:open .. image:: https://travis-ci.org/pjdelport/backports.tempfile.svg?branch=master :target: https://travis-ci.org/pjdelport/backports.tempfile .. image:: https://codecov.io/github/pjdelport/backports.tempfile/coverage.svg?branch=master :target: https://codecov.io/github/pjdelport/backports.tempfile?branch=master Supported Python versions ========================= * CPython: 2.7, 3.4, 3.5, 3.6 * PyPy, PyPy3 Backported functionality ======================== * `TemporaryDirectory`_ (new in Python 3.4) .. _`TemporaryDirectory`: https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory backports.tempfile-1.0/setup.py000066400000000000000000000023551317012211700166600ustar00rootroot00000000000000# coding: utf-8 from setuptools import setup, find_packages def README(): with open('README.rst') as f: return f.read() setup( name='backports.tempfile', description="Backport of new features in Python's tempfile module", long_description=README(), url='https://github.com/pjdelport/backports.tempfile', author='Pi Delport', author_email='pjdelport@gmail.com', package_dir={'': 'src'}, packages=find_packages('src'), setup_requires=['setuptools_scm'], use_scm_version=True, install_requires=[ 'backports.weakref', ], license='Python Software Foundation License', classifiers=[ 'Development Status :: 6 - Mature', 'Intended Audience :: Developers', 'License :: OSI Approved :: Python Software Foundation License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development :: Libraries :: Python Modules', ], ) backports.tempfile-1.0/src/000077500000000000000000000000001317012211700157305ustar00rootroot00000000000000backports.tempfile-1.0/src/backports/000077500000000000000000000000001317012211700177205ustar00rootroot00000000000000backports.tempfile-1.0/src/backports/__init__.py000066400000000000000000000001711317012211700220300ustar00rootroot00000000000000# See https://pypi.python.org/pypi/backports from pkgutil import extend_path __path__ = extend_path(__path__, __name__) backports.tempfile-1.0/src/backports/tempfile.py000066400000000000000000000041551317012211700221040ustar00rootroot00000000000000""" Partial backport of Python 3.5's tempfile module: TemporaryDirectory Backport modifications are marked with marked with "XXX backport". """ from __future__ import absolute_import import sys import warnings as _warnings from shutil import rmtree as _rmtree from backports.weakref import finalize # XXX backport: Rather than backporting all of mkdtemp(), we just create a # thin wrapper implementing its Python 3.5 signature. if sys.version_info < (3, 5): from tempfile import mkdtemp as old_mkdtemp def mkdtemp(suffix=None, prefix=None, dir=None): """ Wrap `tempfile.mkdtemp()` to make the suffix and prefix optional (like Python 3.5). """ kwargs = {k: v for (k, v) in dict(suffix=suffix, prefix=prefix, dir=dir).items() if v is not None} return old_mkdtemp(**kwargs) else: from tempfile import mkdtemp # XXX backport: ResourceWarning was added in Python 3.2. # For earlier versions, fall back to RuntimeWarning instead. _ResourceWarning = RuntimeWarning if sys.version_info < (3, 2) else ResourceWarning class TemporaryDirectory(object): """Create and return a temporary directory. This has the same behavior as mkdtemp but can be used as a context manager. For example: with TemporaryDirectory() as tmpdir: ... Upon exiting the context, the directory and everything contained in it are removed. """ def __init__(self, suffix=None, prefix=None, dir=None): self.name = mkdtemp(suffix, prefix, dir) self._finalizer = finalize( self, self._cleanup, self.name, warn_message="Implicitly cleaning up {!r}".format(self)) @classmethod def _cleanup(cls, name, warn_message): _rmtree(name) _warnings.warn(warn_message, _ResourceWarning) def __repr__(self): return "<{} {!r}>".format(self.__class__.__name__, self.name) def __enter__(self): return self.name def __exit__(self, exc, value, tb): self.cleanup() def cleanup(self): if self._finalizer.detach(): _rmtree(self.name) backports.tempfile-1.0/tests/000077500000000000000000000000001317012211700163035ustar00rootroot00000000000000backports.tempfile-1.0/tests/test_tempfile.py000066400000000000000000000242361317012211700215300ustar00rootroot00000000000000""" Partial backport of Python 3.5's test.test_tempfile: BaseTestCase TestTemporaryDirectory Backport modifications are marked with "XXX backport". """ import tempfile import errno import os import sys import re import warnings from backports.tempfile import TemporaryDirectory import unittest from backports.test import support from backports.test.support import script_helper # XXX backport: ResourceWarning was added in Python 3.2. # For earlier versions, fall back to RuntimeWarning instead. _ResourceWarning = RuntimeWarning if sys.version_info < (3, 2) else ResourceWarning # Common functionality. class BaseTestCase(unittest.TestCase): # XXX backport: tempfile's random template changed in Python 3. if sys.version_info < (3,): str_check = re.compile(r"^[a-zA-Z0-9_-]{6}$") b_check = re.compile(br"^[a-zA-Z0-9_-]{6}$") else: str_check = re.compile(r"^[a-z0-9_-]{8}$") b_check = re.compile(br"^[a-z0-9_-]{8}$") def setUp(self): self._warnings_manager = support.check_warnings() self._warnings_manager.__enter__() warnings.filterwarnings("ignore", category=RuntimeWarning, message="mktemp", module=__name__) def tearDown(self): self._warnings_manager.__exit__(None, None, None) def nameCheck(self, name, dir, pre, suf): # pragma: no cover (test support code) (ndir, nbase) = os.path.split(name) npre = nbase[:len(pre)] nsuf = nbase[len(nbase)-len(suf):] # XXX backport: TODO: These do not test for unicode vs. str/bytes under Python < 3. # XXX backport: TODO: Enable unicode_literals and make these pass? if dir is not None: self.assertIs(type(name), str if type(dir) is str else bytes, "unexpected return type") if pre is not None: self.assertIs(type(name), str if type(pre) is str else bytes, "unexpected return type") if suf is not None: self.assertIs(type(name), str if type(suf) is str else bytes, "unexpected return type") if (dir, pre, suf) == (None, None, None): self.assertIs(type(name), str, "default return type must be str") # check for equality of the absolute paths! self.assertEqual(os.path.abspath(ndir), os.path.abspath(dir), "file %r not in directory %r" % (name, dir)) self.assertEqual(npre, pre, "file %r does not begin with %r" % (nbase, pre)) self.assertEqual(nsuf, suf, "file %r does not end with %r" % (nbase, suf)) nbase = nbase[len(pre):len(nbase)-len(suf)] check = self.str_check if isinstance(nbase, str) else self.b_check self.assertTrue(check.match(nbase), "random characters %r do not match %r" % (nbase, check.pattern)) class TestTemporaryDirectory(BaseTestCase): """Test TemporaryDirectory().""" def do_create(self, dir=None, pre="", suf="", recurse=1): if dir is None: dir = tempfile.gettempdir() tmp = TemporaryDirectory(dir=dir, prefix=pre, suffix=suf) self.nameCheck(tmp.name, dir, pre, suf) # Create a subdirectory and some files if recurse: d1 = self.do_create(tmp.name, pre, suf, recurse-1) d1.name = None with open(os.path.join(tmp.name, "test.txt"), "wb") as f: f.write(b"Hello world!") return tmp def test_mkdtemp_failure(self): # Check no additional exception if mkdtemp fails # Previously would raise AttributeError instead # (noted as part of Issue #10188) with TemporaryDirectory() as nonexistent: pass # XXX backport: Fall back to OSError on Python < 3 (errno gets tested below) _FileNotFoundError = OSError if sys.version_info < (3,) else FileNotFoundError with self.assertRaises(_FileNotFoundError) as cm: TemporaryDirectory(dir=nonexistent) self.assertEqual(cm.exception.errno, errno.ENOENT) def test_explicit_cleanup(self): # A TemporaryDirectory is deleted when cleaned up dir = tempfile.mkdtemp() try: d = self.do_create(dir=dir) self.assertTrue(os.path.exists(d.name), "TemporaryDirectory %s does not exist" % d.name) d.cleanup() self.assertFalse(os.path.exists(d.name), "TemporaryDirectory %s exists after cleanup" % d.name) finally: os.rmdir(dir) @support.skip_unless_symlink def test_cleanup_with_symlink_to_a_directory(self): # cleanup() should not follow symlinks to directories (issue #12464) d1 = self.do_create() d2 = self.do_create(recurse=0) # Symlink d1/foo -> d2 os.symlink(d2.name, os.path.join(d1.name, "foo")) # This call to cleanup() should not follow the "foo" symlink d1.cleanup() self.assertFalse(os.path.exists(d1.name), "TemporaryDirectory %s exists after cleanup" % d1.name) self.assertTrue(os.path.exists(d2.name), "Directory pointed to by a symlink was deleted") self.assertEqual(os.listdir(d2.name), ['test.txt'], "Contents of the directory pointed to by a symlink " "were deleted") d2.cleanup() @support.cpython_only def test_del_on_collection(self): # A TemporaryDirectory is deleted when garbage collected dir = tempfile.mkdtemp() try: d = self.do_create(dir=dir) name = d.name del d # Rely on refcounting to invoke __del__ self.assertFalse(os.path.exists(name), "TemporaryDirectory %s exists after __del__" % name) finally: os.rmdir(dir) def test_del_on_shutdown(self): # XXX backport: __builtin__ renamed to builtins _builtins = ('__builtin__' if sys.version_info < (3,) else 'builtins') # A TemporaryDirectory may be cleaned up during shutdown with self.do_create() as dir: for mod in (_builtins, 'os', 'shutil', 'sys', 'tempfile', 'warnings'): code = """if True: import {_builtins} import os import shutil import sys import tempfile import warnings from backports.tempfile import TemporaryDirectory tmp = TemporaryDirectory(dir={dir!r}) # XXX backport: No buffer attribute in Python < 3 _stdout = sys.stdout if sys.version_info < (3,) else sys.stdout.buffer _stdout.write(tmp.name.encode()) tmp2 = os.path.join(tmp.name, 'test_dir') os.mkdir(tmp2) with open(os.path.join(tmp2, "test.txt"), "w") as f: f.write("Hello world!") {mod}.tmp = tmp warnings.filterwarnings("always", category={_ResourceWarning}) """.format(dir=dir, mod=mod, # XXX backport: _builtins=_builtins, _ResourceWarning=_ResourceWarning.__name__) rc, out, err = script_helper.assert_python_ok("-c", code) tmp_name = out.decode().strip() self.assertFalse(os.path.exists(tmp_name), "TemporaryDirectory %s exists after cleanup" % tmp_name) err = err.decode('utf-8', 'backslashreplace') self.assertNotIn("Exception ", err) # XXX backport: self.assertIn("{}: Implicitly cleaning up".format(_ResourceWarning.__name__), err) def test_exit_on_shutdown(self): # Issue #22427 with self.do_create() as dir: code = """if True: import sys from backports.tempfile import TemporaryDirectory import warnings def generator(): with TemporaryDirectory(dir={dir!r}) as tmp: yield tmp g = generator() # XXX backport: No buffer attribute in Python < 3 _stdout = sys.stdout if sys.version_info < (3,) else sys.stdout.buffer _stdout.write(next(g).encode()) warnings.filterwarnings("always", category={_ResourceWarning}) """.format(dir=dir, _ResourceWarning=_ResourceWarning.__name__) rc, out, err = script_helper.assert_python_ok("-c", code) tmp_name = out.decode().strip() self.assertFalse(os.path.exists(tmp_name), "TemporaryDirectory %s exists after cleanup" % tmp_name) err = err.decode('utf-8', 'backslashreplace') self.assertNotIn("Exception ", err) # XXX backport: self.assertIn("{}: Implicitly cleaning up".format(_ResourceWarning.__name__), err) def test_warnings_on_cleanup(self): # ResourceWarning will be triggered by __del__ with self.do_create() as dir: d = self.do_create(dir=dir, recurse=3) name = d.name # Check for the resource warning with support.check_warnings(('Implicitly', _ResourceWarning), quiet=False): warnings.filterwarnings("always", category=_ResourceWarning) del d support.gc_collect() self.assertFalse(os.path.exists(name), "TemporaryDirectory %s exists after __del__" % name) def test_multiple_close(self): # Can be cleaned-up many times without error d = self.do_create() d.cleanup() d.cleanup() d.cleanup() def test_context_manager(self): # Can be used as a context manager d = self.do_create() with d as name: self.assertTrue(os.path.exists(name)) self.assertEqual(name, d.name) self.assertFalse(os.path.exists(name)) backports.tempfile-1.0/tox.ini000066400000000000000000000021341317012211700164540ustar00rootroot00000000000000# Tox (http://tox.testrun.org/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. # Add "-codecov" to the env name to enable codecov.io reporting. # See: https://github.com/codecov/codecov-python#using-tox [tox] envlist = py{27,34,35,36,py} [testenv] passenv = TOXENV CI TRAVIS TRAVIS_* deps = # Test-only dependencies backports.test.support # codecov.io reporting (mainly for Travis) codecov: coverage codecov: codecov >=1.4.0 # XXX: Is there any better way than this to get coverage paths reported right? usedevelop = codecov: true commands = # XXX: This will currently run the tests twice under codecov, but oh well. # TODO: Use a factor-based override or negation for this sometime? # See: # https://github.com/tox-dev/tox/issues/189 # https://github.com/tox-dev/tox/issues/292 python -m unittest discover tests codecov: coverage run -m unittest discover tests codecov: codecov -e TOXENV