6、pytest -- 临时目录和文件
1. 相关的fixture
1.1. tmp_path
tmp_path
是一个用例级别的fixture
,其作用是返回一个唯一的临时目录对象(pathlib.Path
);
我们看下面的例子:
# src/chapter-6/test_tmp_path.py
CONTENT = "content"
def test_create_file(tmp_path):
d = tmp_path / "sub"
d.mkdir() # 创建一个子目录
p = d / "hello.txt"
p.write_text(CONTENT)
assert p.read_text() == CONTENT
assert len(list(tmp_path.iterdir())) == 1 # iterdir() 迭代目录,返回迭代器
assert 0 # 为了展示,强制置为失败
执行:
λ pipenv run pytest -q -s src/chapter-6/test_tmp_path.py
F
==================================== FAILURES =====================================
________________________________ test_create_file _________________________________
tmp_path = WindowsPath('C:/Users/luyao/AppData/Local/Temp/pytest-of-luyao/pytest-4/test_create_file0')
def test_create_file(tmp_path):
d = tmp_path / "sub"
d.mkdir() # 创建一个子目录
p = d / "hello.txt"
p.write_text(CONTENT)
assert p.read_text() == CONTENT
assert len(list(tmp_path.iterdir())) == 1 # iterdir() 迭代目录,返回迭代器
> assert 0 # 为了展示,强制置为失败
E assert 0
src\chapter-6\test_tmp_path.py:32: AssertionError
1 failed in 0.06s
可以看出:
tmp_path
在不同的操作系统中,返回的是不同类型的pathlib.Path
对象,这里Windows
系统下返回的是WindowsPath
对象,它是Path
的子类对象;Path
对象可以使用/
操作符代替常用的os.path.join()
的方法;更多关于pathlib
的使用方法可以查看:https://docs.python.org/3.7/library/pathlib.html
1.2. 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
可以看出:
tmp_path
调用了tmp_path_factory
;tmp_path_factory
返回一个_pytest.tmpdir.TempPathFactory
对象;进一步查看
_mk_tmp
的源码: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
对象;
1.3. tmpdir
tmp_path
是一个用例级别的fixture
,其作用是返回一个唯一的临时目录对象(py.path.local),它提供os.path
的方法;
上面的例子也可以修改成如下这样:
# src/chapter-6/test_tmpdir.py
CONTENT = "content"
def test_create_file(tmpdir):
p = tmpdir.mkdir("sub").join("hello.txt") # 创建子文件夹,并新建文件
p.write(CONTENT)
assert p.read() == CONTENT
assert len(tmpdir.listdir()) == 1 # iterdir() 迭代目录,返回列表
assert 0 # 为了展示,强制置为失败
执行:
λ pipenv run pytest -q -s src/chapter-6/test_tmpdir.py
F
==================================== FAILURES =====================================
________________________________ test_create_file _________________________________
tmpdir = local('C:\\Users\\luyao\\AppData\\Local\\Temp\\pytest-of-luyao\\pytest-6\\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 # iterdir() 迭代目录,返回列表
> assert 0 # 为了展示,强制置为失败
E assert 0
src\chapter-6\test_tmpdir.py:30: AssertionError
1 failed in 0.06s
其实,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)
1.4. tmpdir_factory
tmpdir_factory
是一个会话级别的fixture
,其作用是在其它fixture
或者用例中创建任意的临时目录;
假设,一个测试会话需要使用到一个很大的由程序生成的图像文件,相比于每个测试用例生成一次文件,更好的做法是每个会话只生成一次:
import pytest
@pytest.fixture(scope="session")
def image_file(tmpdir_factory):
img = compute_expensive_image()
fn = tmpdir_factory.mktemp("data").join("img.png")
img.save(str(fn))
return fn
def test_histogram(image_file):
img = load_image(image_file)
# compute and test histogram
1.5. 区别
fixture | 作用域 | 返回值类型 |
---|---|---|
tmp_path | 用例级别(function) | pathlib.Path |
tmp_path_factory | 会话级别(session) | TempPathFactory |
tmpdir | 用例级别(function) | py.local.path |
tmpdir_factory | 会话级别(session) | TempDirFactory |
2. 默认的基本临时目录
上述fixture
在创建临时目录时,都是创建在系统默认的临时目录(例如:Windows
系统的%temp%
目录)下;你可以通过指定--basetemp=mydir
选项自定义默认的基本临时目录;
λ pipenv run pytest -q -s --basetemp="/d/temp" src/chapter-6/test_tmpdir.py
F
==================================== FAILURES =====================================
________________________________ test_create_file _________________________________
tmpdir = local('D:\\temp\\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 # iterdir() 迭代目录,返回列表
> assert 0 # 为了展示,强制置为失败
E assert 0
src\chapter-6\test_tmpdir.py:30: AssertionError
1 failed in 0.04s
GitHub仓库地址:https://github.com/luizyao/pytest-chinese-doc
6、pytest -- 临时目录和文件的更多相关文章
- QTemporaryDir及QTemporaryFile建立临时目录及文件夹
版权声明:若无来源注明,Techie亮博客文章均为原创. 转载请以链接形式标明本文标题和地址: 本文标题:QTemporaryDir及QTemporaryFile建立临时目录及文件夹 本文地址 ...
- QTemporaryDir及QTemporaryFile建立临时目录及文件夹(创建一个随机名称的目录或文件,两者均能保证不会覆盖已有文件)
版权声明:若无来源注明,Techie亮博客文章均为原创. 转载请以链接形式标明本文标题和地址:本文标题:QTemporaryDir及QTemporaryFile建立临时目录及文件夹 本文地址: ...
- UWP开发之Template10实践二:拍照功能你合理使用了吗?(TempState临时目录问题)
最近在忙Asp.Net MVC开发一直没空更新UWP这块,不过有时间的话还是需要将自己的经验和大家分享下,以求共同进步. 在上章[UWP开发之Template10实践:本地文件与照相机文件操作的MVV ...
- Pytest权威教程08-使用tmp目录和文件
目录 使用tmp目录和文件 tmp_path Fixture方法 tmp_path_factory Fixture方法 tmpdir Fixture方法 tmpdir_factory Fixture方 ...
- File根据inputstream复制文件到临时目录,使用完之后删除
项目中有这个需求: 1)上传文件通过公司平台的校验,校验成功后,通过接口,返回文件流: 2)我们根据这个文件流进行操作.这里,先将文件流复制文件到项目临时目录WEB-INF/temp;文件使用完毕,删 ...
- Springboot上传文件临时目录无效
一个奇葩问题,虽然解决了,但还是没弄清楚,小记一笔. 年后回来,测试人员对年前的3次迭代的功能进行了回归测试,然后发现所有excel导入的功能都失效了.作为后台开发人员,当然是第一时间打开运行日志排查 ...
- npm下载文件临时目录、实际存放目录路劲
npm 下载文件临时存放目录 路劲:C:\Users\xxxxxx\AppData\Roaming\npm\node_modules ( C:\Users\dihongwanyan\AppData\R ...
- Spring boot内置Tomcat的临时目录被删除导致文件上传不了-问题解析
目录 1.问题 2.1. 为什么需要使用这个/tmp/tomcat*? 2.2.那个 /tmp/tomcat* 目录为什么不存在? 三.解决办法 修改 springboot 配置,不要在/tmp 下创 ...
- 【Visual Lisp】驱动器、目录、文件和注册表
;;驱动器.目录.文件.和注册表;;★★★01.获取并创建驱动器盘符组成的表★★★(setq Drives (vlax-get-property (vlax-create-object "S ...
随机推荐
- Solidity 编程实例--简单的公开拍卖
通常简单的公开拍卖合约,是每个人可以在拍卖期间发送他们的竞拍出价.为了实现绑定竞拍人的到他们的拍卖,竞拍包括发送金额/ether.如果产生了新的最高竞拍价,前一个最高价竞拍人将会拿回他的钱.在竞拍阶段 ...
- 修复IScroll点击无效,增加scrollTo数值容错处理
个人博客: https://chenjiahao.xyz ============== 最近半年都处于一个非常忙碌的状态,直到现在才有功夫腾出时间记录这段时间以来踩过的一个个坑. 今天先记录关于ISc ...
- pycharm 安装第三方包步骤
pycharm 安装第三方包步骤: 完成.
- Python高阶函数及函数柯里化
1 Python高阶函数 接收函数为参数,或者把函数作为结果返回的函数为高阶函数. 1.1 自定义sort函数 要求:仿照内建函数sorted,自行实现一个sort函数.内建函数sorted函数是返回 ...
- PTA 7-3 编辑距离问题 (30 分)
一.实践题目 设A和B是2个字符串.要用最少的字符操作将字符串A转换为字符串B.这里所说的字符操作包括: ()删除一个字符: ()插入一个字符: ()将一个字符改为另一个字符. 将字符串A变换为字符串 ...
- SpringCloud教程一:eureka注册中心(Finchley版)
一.spring cloud简介 本阶段学习教程Spring Boot版本2.0.3.RELEASE,Spring Cloud版本为Finchley.RELEASE. Finchley版本的官方文档如 ...
- Loj10222佳佳的 Fibonacci
Description Analysis 10分:暴力+把m和n输反,你将获得10分的好成绩(Just like me.) 70分:暴力+把m和n输对,你将获得70分的好成绩 100分:矩阵加速 设 ...
- 从零开始搭建前端监控系统(三)——实现控制iframe前进后退
前言 本系列文章旨在讲解如何从零开始搭建前端监控系统. 项目已经开源 项目地址: https://github.com/bombayjs/bombayjs (web sdk) https://gith ...
- css 块元素超出文字省略表示
.text-omit{ white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } 只对块元素的设置有效 . 块元素和行内元素见 ...
- PHP array_replace
1.函数的作用:替换数组的元素 2.函数的参数: @params array $array1 被替换的数组 @params array $array2 替换的数组 @params array $a ...