【问题标题】:How to automatically delete temporary files generated during PyTest?如何自动删除 PyTest 期间生成的临时文件?
【发布时间】:2020-06-05 16:51:32
【问题描述】:

我的用例是:

  1. 我在一个名为“Source”的文件夹中有一组 python 脚本。
  2. 在另一个名为“Test Scripts”的文件夹中,我为每个 python 脚本提供了一组专用的测试用例脚本(使用 PyTest)。我能够运行测试用例。
  3. 这两个文件夹都有 init python 脚本。

问题:在测试用例运行期间创建了临时文件。我尝试使用夹具来解决此问题。特别是,我尝试遵循这个 SO question, PyTest: Auto delete temporary directory created with tmpdir_factory 但是,它并没有帮助我实现目标。

此外,我想知道是否可以将 python dict 作为命令行参数,因为源文件夹中的脚本通过以字典作为参数的命令运行。 目前,我通过这个命令,

python -m pytest Test Scripts / test_script.py

其中一个测试用例的代码片段:

import pytest
from script_name import class_name
import shutil

@pytest.fixture
def obj_creation():
    my_obj = class_name(data = " { 'a': 'b','c': 'd'} ")
    return [my_obj]

@pytest.fixture(scope='session')
def project_file(tmpdir_factory):
    my_tmpdir = tmpdir_factory.mktemp("data")
    yield my_tmpdir 
    shutil.rmtree(str(my_tmpdir))

def test_no_new_office_ID(project_file, obj_creation):
    x = obj_creation[0].ofc_email()
    assert not x

我没有找到任何完整的网络资料(包含所有可能的用例)。请帮我解决一下这个。

快照:

【问题讨论】:

  • 你的夹具对我来说看起来不错,前提是所有临时文件确实是在 project_file 返回的目录中创建的(在显示的代码中看不到)。你的具体问题是什么?谁实际负责创建临时文件?
  • 当我运行任何测试脚本时,都会创建临时文件。这给我的印象是我没有正确使用夹具。现在,为了更清楚起见,我已经包含了一个快照。可能是因为导入了源脚本。
  • 这些不是临时文件 - 这些是 compiled Python files,在执行期间需要。您只需要确保它们包含在 .gitignore 等中,但您不应该删除它们。
  • 只需在您的.gitignore 中添加一个*.pyc 行,这样这些文件就会被忽略。检查documentation
  • 它们通常被添加到存储库中(如文档中所述),因为您希望在存储库的每个克隆中都使用它们。

标签: python python-3.x pytest


【解决方案1】:

我正在使用 Django 的 TestCase 类进行自动测试。这是我用来删除在测试中创建的临时文件的代码:

import shutil


@classmethod
def tearDownClass(cls):
    try:
        shutil.rmtree(django_settings.TESTS_MEDIA_ROOT)
    except OSError:
        pass
    return super().tearDownClass()

也许你可以使用类似的东西来删除你的文件?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    相关资源
    最近更新 更多