74 lines
2.4 KiB
Plaintext
74 lines
2.4 KiB
Plaintext
|
|
.. _`tmpdir handling`:
|
|
.. _tmpdir:
|
|
|
|
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"
|
|
assert len(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 ============================
|
|
platform linux -- Python 3.4.0 -- py-1.4.25 -- pytest-2.6.3
|
|
collected 1 items
|
|
|
|
test_tmpdir.py F
|
|
|
|
================================= FAILURES =================================
|
|
_____________________________ test_create_file _____________________________
|
|
|
|
tmpdir = local('/tmp/pytest-19/test_create_file0')
|
|
|
|
def test_create_file(tmpdir):
|
|
p = tmpdir.mkdir("sub").join("hello.txt")
|
|
p.write("content")
|
|
assert p.read() == "content"
|
|
assert len(tmpdir.listdir()) == 1
|
|
> assert 0
|
|
E assert 0
|
|
|
|
test_tmpdir.py:7: AssertionError
|
|
========================= 1 failed in 0.01 seconds =========================
|
|
|
|
.. _`base temporary directory`:
|
|
|
|
The default base temporary directory
|
|
-----------------------------------------------
|
|
|
|
Temporary directories are by default created as sub-directories of
|
|
the system temporary directory. The base name will be ``pytest-NUM`` where
|
|
``NUM`` will be incremented with each test run. Moreover, entries older
|
|
than 3 temporary directories will be removed.
|
|
|
|
You can override the default temporary directory setting like this::
|
|
|
|
py.test --basetemp=mydir
|
|
|
|
When distributing tests on the local machine, ``pytest`` takes care to
|
|
configure a basetemp directory for the sub processes such that all temporary
|
|
data lands below a single per-test run basetemp directory.
|
|
|
|
.. _`py.path.local`: http://py.rtfd.org/en/latest/path.html
|
|
|
|
|