Pytest官方教程-08-使用tmp目录和文件

目录:

  1. 安装及入门
  2. 使用和调用方法
  3. 原有TestSuite使用方法
  4. 断言的编写和报告
  5. Pytest fixtures:清晰 模块化 易扩展
  6. 使用Marks标记测试用例
  7. Monkeypatching/对模块和环境进行Mock
  8. 使用tmp目录和文件
  9. 捕获stdout及stderr输出
  10. 捕获警告信息
  11. 模块及测试文件中集成doctest测试
  12. skip及xfail: 处理不能成功的测试用例
  13. Fixture方法及测试用例的参数化
  14. 缓存: 使用跨执行状态
  15. unittest.TestCase支持
  16. 运行Nose用例
  17. 经典xUnit风格的setup/teardown
  18. 安装和使用插件
  19. 插件编写
  20. 编写钩子(hook)方法
  21. 运行日志
  22. API参考
    1. 方法(Functions)
    2. 标记(Marks)
    3. 钩子(Hooks)
    4. 装置(Fixtures)
    5. 对象(Objects)
    6. 特殊变量(Special Variables)
    7. 环境变量(Environment Variables)
    8. 配置选项(Configuration Options)
  23. 优质集成实践
  24. 片状测试
  25. Pytest导入机制及sys.path/PYTHONPATH
  26. 配置选项
  27. 示例及自定义技巧
  28. Bash自动补全设置

使用tmp目录和文件

tmp_path装置

3.9版本新功能
你可以使用tmp_path 在临时目录根目录中创建一个独立的临时目录以供测试调用。

tmp_path是一个pathlib/pathlib2.Path对象。以下是测试用法的示例:

# test_tmp_path.py文件内容
import os

CONTENT = u"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
    assert 0

运行这个,我们可以看到,除了assert 0这一行,其他断言都正常测试通过:

$ pytest test_tmpdir.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
rootdir: $REGENDOC_TMPDIR, inifile:
collected 1 item

test_tmpdir.py F                                                     [100%]

================================= FAILURES =================================
_____________________________ test_create_file _____________________________

tmpdir = local('PYTEST_TMPDIR/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.12 seconds =========================

'tep_dir_factory' 装置

2.8版本新功能
tmpdir_factory是一个session范围的fixture,可用于从任何其他测试用例及fixture中创建任意临时目录。

例如,假设你的测试套件需要使用程序动态生成在本地磁盘上的一个大图片,你可以整个测试session中只生成一次以节省时间,而不是为每个用例都在自己的tmpdir中计算并生成一次:

# conftest.py文件内容
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


# contents of test_image.py
def test_histogram(image_file):
    img = load_image(image_file)
    # 计算和测试histogram

有关详细信息,请参阅tmpdir_factory API。

默认临时目录根目录

默认情况下,临时目录创建为系统临时目录的子目录。 基本名称将是pytest-数字,其中数字将随着每次测试运行而递增。 此外,第3个以后的临时目录会被删除。

你可以如下所示,修改默认的临时目录设置:

pytest --basetemp=mydir

在本地计算机上分发测试时,pytest会为子进程配置临时目录根目录,以便所有临时数据都落在单个每个测试运行的临时目录根目录。

你可能感兴趣的:(Pytest官方教程-08-使用tmp目录和文件)