在Pytest运行之前执行一些代码

Lak*_*tna 6 python pytest

我正在使用Pytest来测试我的代码,但遇到了一个小问题,但令人发指。

我的程序要做的第一件事就是检查是否有任何可用的设置文件。如果不存在,它将引发错误并调用exit()。在正常运行时,此方法效果很好,但与Pytest混淆。

我想到的解决方案是通过复制模板设置文件,在测试期间简单地创建一个临时设置文件。我已经编写并成功测试了代码以实现该目标。

我遇到的问题是我找不到真正能在其他所有东西之前触发的Pytest钩子。这导致程序在Pytest尝试创建临时设置文件之前引发错误。这导致Pytest无法执行任何测试。

有谁知道在Pytest执行或加载任何东西之前触发函数的方法吗?最好在Pytest内部。

一些代码上下文:

抛出错误并退出

此代码段在settings模块导入时运行。

if len(cycles) == 0:
    log.error("No setting files found. Please create a file " +
              "in the `settings` folder using the Template.py.")
    exit()
Run Code Online (Sandbox Code Playgroud)

创建临时设置文件

这段代码应该是Pytest运行的第一件事。

def pytest_sessionstart(session):
    """ Create a test settings file """
    folderPath = os.path.dirname(os.path.abspath(__file__))
    folderPath = os.path.split(folderPath)[0] + "/settings"

    srcfile = folderPath + '/Template.py'
    dstfile = folderPath + '/test.py'

    shutil.copy(srcfile, dstfile)
Run Code Online (Sandbox Code Playgroud)

删除临时设置文件

这段代码应该是Pytest运行的最后一件事。

def pytest_sessionfinish(session, exitstatus):
    """ Delete the test settings file """
    folderPath = os.path.dirname(os.path.abspath(__file__))
    folderPath = os.path.split(folderPath)[0] + "/settings"

    os.remove(folderPath + "/test.py")
Run Code Online (Sandbox Code Playgroud)

Pytest输出

通过exit()禁用呼叫,您可以看到执行顺序。

if len(cycles) == 0:
    log.error("No setting files found. Please create a file " +
              "in the `settings` folder using the Template.py.")
    exit()
Run Code Online (Sandbox Code Playgroud)

Nam*_* VU 12

conftest.py使用以下代码添加到您的项目并将您的代码添加到方法pytest_configure

def pytest_configure(config):
    pass # your code goes here

# other config
Run Code Online (Sandbox Code Playgroud)


mar*_*llv -3

要在测试的实际代码之前和之后运行一些代码,您可以使用 pytest 夹具:

import pytest


@pytest.fixture
def context():
    """What to do before/after the test."""
    print("Entering !")
    yield
    print("Exiting !")


def test_stuff(context):
    """The actual code of your test"""
    print("Running the test")
Run Code Online (Sandbox Code Playgroud)

这显示:

Entering !
Running the test
Exiting !
Run Code Online (Sandbox Code Playgroud)

要使用夹具,只需传递一个与测试函数的输入同名的参数即可。Yield 指令的作用就像测试之前和之后所做的事情之间的分隔符。