Skip to main content

Create and recursively fill a temporary directory

Project description

Run code inside a temporary directory filled with zero or more files.

Very convenient for writing tests: you can decorate individual tests or a whole test suite.

tdir() runs code in a temporary directory pre-filled with files: it can either be used as a context manager, or a decorator for functions or classes.

tdir.fill() is a tiny function that recursively fills a directory.

EXAMPLE: as a context manager

from pathlib import Path
import tdir

cwd = Path.cwd()

# Simplest invocation.

with tdir():
   # Do a lot of things in a temporary directory

# Everything is gone!

# With a single file
with tdir('hello') as td:
    # The file ``hello`` is there
    assert Path('hello').read_text() = 'hello\n'

    # We're in a temporary directory
    assert td == Path.cwd()
    assert td != cwd

    # Write some other file
    Path('junk.txt').write_text('hello, world\n')

# The temporary directory and the files are gone
assert not td.exists()
assert cwd == Path.cwd()

# A more complex example:
#
with tdir(
    'one.txt',
    three='some information',
    four=Path('existing/file'),  # Copy a file into the tempdir
    sub1={
        'file.txt': 'blank lines\n\n\n\n',
        'sub2': [
            'a', 'b', 'c'
        ]
    },
):
    assert Path('one.txt').exists()
    assert Path('four').read_text() == Path('/existing/file').read_text()
    assert Path('sub1/sub2/a').exists()

# All files gone!

EXAMPLE: as a decorator

from pathlib import Path
import tdir
import unittest

@tdir
def my_function():
    pass  # my_function() always operates in a temporary directory


# Decorate a TestCase so each test runs in a new temporary directory
# with two files
@tdir('a', foo='bar')
class MyTest(unittest.TestCast):
    def test_something(self):
        assert Path('a').read_text() = 'a\n'

    def test_something_else(self):
        assert Path('foo').read_text() = 'bar\n'


class MyTest2(unittest.TestCast):
    # Decorate just one test in a unitttest
    @tdir(foo='bar', baz=bytes(range(4)))  # binary files are possible
    def test_something(self):
        assert Path('foo').read_text() = 'bar\n'
        assert Path('baz').read_bytes() = bytes(range(4)))

    # Run test in an empty temporary directory
    @tdir
    def test_something_else(self):
        assert not Path('a').exists()
        assert Path().absolute() != self.ORIGINAL_PATH

    ORIGINAL_PATH = Path().absolute()

API

Class tdir

(tdir.py, 120-220)

Set up a temporary directory, fill it with files, then tear it down at the end of an operation.

tdir can be used either as a context manager, or a decorator for functions or classes.

ARGUMENTS
args, kwargs:

Files to put into the temporary directory. See the documentation for tdir.fill()

chdir:

If true (the default), change the working directory to the tdir at the start of the operation and restore the original working directory at the end. Otherwise, don’t change or restore the working directory.

methods:

The methods argument tells how to decorate class methods when decorating a class.

The default decorates only class methods that start with the string test - exactly like unittest.mock.patch does.

See https://github.com/rec/dek/blob/master/README.rst#dekdekdecorator-deferfalse-methodsnone

use_dir:

If non-empty, use_dir is used instead of a temp directory (and is not removed at the end) - for example, use_dir='.' puts everything in the current directory.

save:

If set to true, the temp directory is not deleted at end and its name is printed to sys.stderr

tdir.tdir.__new__()

tdir.tdir.__new__(
     cls,
     *args,
     chdir=True,
     methods='test',
     use_dir=None,
     save=False,
     **kwargs,
)

(tdir.py, 158-190)

Create and return a new object. See help(type) for accurate signature.

tdir.tdir.__call__(self, *args, **kwargs)

(tdir.py, 218-220)

Call self as a function.

tdir.fill(root, *args, **kwargs)

(tdir.py, 222-286)

Recursively fills a directory from file names and optional values.

ARGUMENTS
root:

The root directory to fill

args:

A list of strings, dictionaries or Paths.

For strings, a file is created with that string as name and contents.

For dictionaries, the contents are used to recursively create and fill the directory.

For Paths, that file is copied into the target directory under the same name.

kwargs:

A dictionary mapping file or directory names to values.

If the key’s value is a string it is used to file a file of that name.

If it’s a dictionary, its contents are used to recursively create and fill a subdirectory.

If it’s a Path, that file is copied to the target directory but with the key as its name.

(automatically generated by doks on 2020-12-03T18:26:23.830491)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tdir-1.2.3.tar.gz (6.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tdir-1.2.3-py3-none-any.whl (6.9 kB view details)

Uploaded Python 3

File details

Details for the file tdir-1.2.3.tar.gz.

File metadata

  • Download URL: tdir-1.2.3.tar.gz
  • Upload date:
  • Size: 6.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/33.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.63.0 importlib-metadata/4.11.2 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.7.0

File hashes

Hashes for tdir-1.2.3.tar.gz
Algorithm Hash digest
SHA256 6268db433e480751d09a559d515702294d112d3610049d539fa2548643997b26
MD5 436fa801f3617225308c990dec88aa9a
BLAKE2b-256 6851183da350ea7b930031524bbc1e426939393c416e75408a54193610898ece

See more details on using hashes here.

File details

Details for the file tdir-1.2.3-py3-none-any.whl.

File metadata

  • Download URL: tdir-1.2.3-py3-none-any.whl
  • Upload date:
  • Size: 6.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/33.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.63.0 importlib-metadata/4.11.2 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.7.0

File hashes

Hashes for tdir-1.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 fd92a9ddc690215ccad5e2ae2e11e9f8482fedb55492858f62077c988690e05a
MD5 928aac1d7b3386f7f32df483b0d4c6ef
BLAKE2b-256 29e1eba73372b8964708092711e00c34f17266403cc55288008dbbf0e0ae4863

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page