【问题标题】:AttributeError: 'module' object has no attribute 'ensuretemp'AttributeError:“模块”对象没有属性“确保临时”
【发布时间】:2015-08-28 17:37:23
【问题描述】:

按照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'

我做错了吗?

【问题讨论】:

  • 您可能需要import py.test 才能获取属性ensuretemp
  • 运行dir(py.test)py.fest.__file__有什么收获?
  • @polarise import py.test, py.test.ensuretemp('py.path_documentation') 引发同样的错误
  • 运行py.test会得到什么?
  • @user3012759 当我从项目根目录运行 py.test 时,它会加载我的测试并且我的测试通过。

标签: python python-3.4 pytest


【解决方案1】:

不,正如文档所示,您所做的一切都是正确的。我也无法让它工作。另一方面,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())

【讨论】:

    【解决方案2】:

    你也可以直接从py.path使用mkdtemp

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-18
      相关资源
      最近更新 更多