为什么在 pytest 装置中使用 Yield 而不是 return?

问题描述 投票:0回答:1

我明白为什么当我们想要运行测试然后清理内容并返回到固定装置并在

yield
语句之后运行一些代码时使用
yield
关键字。如下面的代码。

@pytest.fixture
def sending_user(mail_admin):
    user = mail_admin.create_user()
    yield user
    mail_admin.delete_user(user)

但是,当我们只想返回一个对象而不返回夹具(例如返回一个

yield
)时,为什么有必要使用
patch

from unittest.mock import patch, mock_open
from pytest import raises, fixture
import os.path

def read_from_file(file_path):
    if not os.path.exists(file_path):
        raise Exception("File does not exists!")
    with open(file_path, "r") as f:
        return f.read().splitlines()[0]

@fixture()
def mock_open_file():
    with patch("builtins.open", new_callable=mock_open, read_data="Correct string") as mocked:
        yield mocked #instead of: return mocked

@fixture()
def mock_os():
    with patch("os.path.exists", return_value=True) as mocked:
        yield mocked #instead of: return mocked

def test_read_file_and_returns_the_correct_string_with_one_line(mock_os, mock_open_file):
    result = read_from_file("xyz")
    mock_open_file.assert_called_once_with("xyz", "r")
    assert result == "Correct string"

def test_throws_exception_when_file_doesnt_exist(mock_os, mock_open_file):
    mock_os.return_value = False
    with raises(Exception):
        read_from_file("xyz")
python python-3.x pytest pytest-mock
1个回答
0
投票
  • 在 pytest 夹具中,如果
    return
    语句后面没有任何内容,我们绝对可以使用
    yield
    代替
    yield
    关键字。
  • 这里的 2 个装置必须使用
    yield
    的原因是因为它们都是上下文管理器
© www.soinside.com 2019 - 2024. All rights reserved.