小门板儿

Menu

pytest:临时目录和文件

一、tmp_path夹具

可以使用tmp_path夹具为每一个测试调用创建一个独立的临时目录,这个目录是基于根目录创建的,即根临时目录是所有临时目录的父目录,可以使用命令行指定,也有默认值

tmp_path 是 pathlib.Path 的一个实例,下面是使用的例子:

def test_create_file(tmp_path):
    print(tmp_path)
    d=tmp_path/"test"
    print(d)
    d.mkdir()
    p=d/"hello.txt"
    p.write_text(CONTENT)
    assert p.read_text() == CONTENT
    assert len(list(tmp_path.iterdir())) == 1
    assert 0
  输出结果:
..\c\test_tmp.py::test_create_file C:\Users\admin\AppData\Local\Temp\pytest-of-admin\pytest-4\test_create_file0
C:\Users\admin\AppData\Local\Temp\pytest-of-admin\pytest-4\test_create_file0\test
FAILED

二、tmp_path_factory 夹具

tmp_path_factory是一个会话级别的fixture,其作用是在其它fixture或者用例中创建任意的临时目录;

查看上一章tmp_path fixture的源码,我们能够看到tmp_path就是使用tmp_path_factory的一个例子

# _pytest.tmpdir

@pytest.fixture
def tmp_path(request, tmp_path_factory):
    """Return a temporary directory path object
    which is unique to each test function invocation,
    created as a sub directory of the base temporary
    directory.  The returned object is a :class:`pathlib.Path`
    object.

    .. note::

        in python < 3.6 this is a pathlib2.Path
    """

    return _mk_tmp(request, tmp_path_factory)

@pytest.fixture(scope="session")
def tmp_path_factory(request):
    """Return a :class:`_pytest.tmpdir.TempPathFactory` instance for the test session.
    """
    return request.config._tmp_path_factory

可以看出:

  def _mk_tmp(request, factory):
    name = request.node.name
    name = re.sub(r"[W]", "_", name)
    MAXVAL = 30
    name = name[:MAXVAL]
    return factory.mktemp(name, numbered=True)

可以看出,tmp_path最终调用了TempPathFactory.mktemp()方法,它返回的是一个pathlib.Path对象;

## 三、tmpdir夹具

tmp_path是一个用例级别的fixture,其作用是返回一个唯一的临时目录对象(py.path.local),它提供os.path的方法;

def test_create_file1(tmpdir):
    p=tmpdir.mkdir("test1").join("hello.txt")
    print(p)
    p.write(CONTENT)
    assert p.read()==CONTENT
    assert 0
 输出结果:
                                                                                                                                ..\c\test_tmp.py::test_create_file1 C:\Users\admin\AppData\Local\Temp\pytest-of-admin\pytest-14\test_create_file10\test1\hello.txt  
FAILED
因为assert 0,所以用例失败

其实,tmpdir也调用了tmp_path,只是对返回值做了一次py.path.local()封装:

# _pytest.tmpdir

@pytest.fixture
def tmpdir(tmp_path):
    """Return a temporary directory path object
    which is unique to each test function invocation,
    created as a sub directory of the base temporary
    directory.  The returned object is a `py.path.local`_
    path object.

    .. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html
    """
    return py.path.local(tmp_path)

四、tmpdir_factory夹具

tmpdir_factory是一个session级别的fixture,其作用是在其它fixture或者用例中创建任意的临时目录;

查看源码,可以看到tmpdir_factory有两个方法,mktemp(self, basename: str, numbered: bool = True),getbasetemp(self)

@pytest.fixture(scope="session")
def txt_file(tmpdir_factory):
    # 获取tmpdir_factory的根目录
    print('0000000000')
    print(tmpdir_factory.getbasetemp())
    print('0000000000')
    #生成多个临时目录
    a_file=tmpdir_factory.mktemp('data1')
    b_file = tmpdir_factory.mktemp('data1')
    print(a_file)
    print(b_file)
    return a_file,b_file
def test_a(txt_file):
    assert 0
输出结果:
..\c\test_tmp.py::test_a 0000000000
C:\Users\admin\AppData\Local\Temp\pytest-of-admin\pytest-24
0000000000
C:\Users\admin\AppData\Local\Temp\pytest-of-admin\pytest-24\data10
C:\Users\admin\AppData\Local\Temp\pytest-of-admin\pytest-24\data11
FAILED

getbasetemp()方法返回临时目录所在的根目录,mktemp( basename, numbered)方法,可在临时根目录下创建多个文件夹,numbered默认为Ture,表示创建多个相同名称的文件夹时,默认用数字标记

五、默认的根临时目录

临时目录会默认创建在系统的临时目录下,名称的格式是 pytest-NUM, NUM是一个每次测试运行之后递增的数字。此外,根据这个数字,3次以前的临时目录将会被删除,通过 pytest --basetemp=mydir 更改临时目录

@pytest.fixture(scope="session")
def txt_file(tmpdir_factory):
    # 获取tmpdir_factory的根目录
    print('0000000000')
    print(tmpdir_factory.getbasetemp())
    print('0000000000')
    #生成多个临时目录
    a_file=tmpdir_factory.mktemp('data1')
    b_file = tmpdir_factory.mktemp('data1')
    print(a_file)
    print(b_file)
    return a_file,b_file

def test_a(txt_file):

    assert 0

执行测试时,带上 --basetemp,该次生成的临时文件将在自定义目录下

  D:\pytest\learn01\a>pytest --basetemp=d:\pytest-temp  -s -v test_d.py
========================================================================================== test session starts ===========================================================================================
platform win32 -- Python 3.7.3, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- d:\python3.7\python\python3.exe
cachedir: .pytest_cache
rootdir: D:\pytest\learn01, configfile: pytest.ini
collected 1 item                                                                                                                                                                                          

test_d.py::test_a 0000000000
D:\pytest-temp
0000000000
D:\pytest-temp\data10
D:\pytest-temp\data11
FAILED

参考文档:http://t.zoukankan.com/luizyao-p-11732764.html

— 于 共写了4234个字
— 标签:

评论已关闭。