AttributeError:'module'对象没有属性'ensuretemp'

时间:2015-03-10 14:35:36

标签: python python-3.4 pytest

按照http://py.readthedocs.org/en/latest/path.html#basic-interactive-example

的示例
import py
temppath = py.test.ensuretemp('py.path_documentation')

引发错误     AttributeError:'module'对象没有属性'ensuretemp'

Python 3.4.3版,py版本1.4.26。

In [1]: import py

In [2]: dir(py.test)
Out[2]:
['Class',
 'Collector',
 'File',
 'Function',
 'Generator',
 'Instance',
 'Item',
 'Module',
 'Session',
 'UsageError',
 '__all__',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '__version__',
 '_fillfuncargs',
 '_preloadplugins',
 'cmdline',
 'collect',
 'deprecated_call',
 'exit',
 'fail',
 'fixture',
 'freeze_includes',
 'importorskip',
 'main',
 'mark',
 'raises',
 'set_trace',
 'skip',
 'xfail',
 'yield_fixture']


In [4]: py.test.__file__
Out[4]: '/home/vagrant/.virtualenvs/snap/lib/python3.4/site-packages/pytest.py'

我做错了吗?

2 个答案:

答案 0 :(得分:0)

不,正如文档所示,您正在正确地执行所有操作。我也无法让它运转起来。另一方面,pytest具有fixture tmpdir,它可以在测试中执行您需要的操作:为您的测试提供唯一的临时目录。

以下是测试示例:

def test_one(tmpdir):
    test_file = tmpdir.join('dir', 'file').ensure(file=True)
    test_file.write('test\ntest\n')

    assert test_file.read().rsplit() == ['test', 'test']

另一方面,pytest使用py.path,它有py.path.local对象,并且使用tempfile.mkdtemp你可以创建临时dir对象:

import tempfile

tempdir = py.path.local(tempfile.mkdtemp())

答案 1 :(得分:0)

您也可以直接从mkdtemp

使用py.path
In [127]: import py.path    
In [128]: py.path.local.mkdtemp()
Out[128]: local('/tmp/tmpP1835f')