test_ok1/doc/tmpdir.txt

77 lines
2.6 KiB
Plaintext
Raw Normal View History

2010-11-06 06:37:25 +08:00
.. _`tmpdir handling`:
temporary directories and files
================================================
the 'tmpdir' test function argument
-----------------------------------
You can use the ``tmpdir`` function argument which will
provide a temporary directory unique to the test invocation,
created in the `base temporary directory`_.
``tmpdir`` is a `py.path.local`_ object which offers ``os.path`` methods
and more. Here is an example test usage::
# content of test_tmpdir.py
import os
def test_create_file(tmpdir):
p = tmpdir.mkdir("sub").join("hello.txt")
p.write("content")
assert p.read() == "content"
2010-11-06 06:37:25 +08:00
assert tmpdir.listdir() == 1
assert 0
Running this would result in a passed test except for the last
``assert 0`` line which we use to look at values::
$ py.test test_tmpdir.py
=========================== test session starts ============================
2010-11-02 07:53:53 +08:00
platform linux2 -- Python 2.6.5 -- pytest-2.0.0.dev17
test path 1: test_tmpdir.py
test_tmpdir.py F
================================= FAILURES =================================
_____________________________ test_create_file _____________________________
2010-11-02 07:53:53 +08:00
tmpdir = local('/tmp/pytest-1248/test_create_file0')
def test_create_file(tmpdir):
p = tmpdir.mkdir("sub").join("hello.txt")
p.write("content")
assert p.read() == "content"
assert len(os.listdir(str(tmpdir))) == 1
test_tmpdir.py:7: AssertionError
2010-11-02 07:53:53 +08:00
========================= 1 failed in 0.04 seconds =========================
.. _`base temporary directory`:
the default base temporary directory
-----------------------------------------------
..
You can create directories by calling one of two methods
on the config object:
- ``config.mktemp(basename)``: create and return a new tempdir
- ``config.ensuretemp(basename)``: create or return a new tempdir
Temporary directories are by default created as sub directories of
the system temporary directory. The name will be ``pytest-NUM`` where
``NUM`` will be incremenated with each test run. Moreover, entries older
than 3 temporary directories will be removed.
You can override the default temporary directory logic and set it like this::
py.test --basetemp=mydir
When distributing tests on the local machine, ``py.test`` takes care to
configure a basetemp directory for the sub processes such that all
temporary data lands below below a single per-test run basetemp directory.
.. _`py.path.local`: http://pylib.org/path.html