Pytest 无法在 monkeypatch 中使用夹具

Pytest unable to use fixture in monkeypatch

我正在尝试使用夹具对我正在测试的 class 中的函数进行 monkeypatch,但不断得到 Fixture "get_staticdata_path" called directly. Fixtures are not meant to be called directly, but are created automatically when test functions request them as parameters。我知道有类似的问题,但 none 对我有用。

conftest.py

import pytest
from pathlib import Path
import spacy


@pytest.fixture
def get_staticdata_path():
    static_data_path = (
        Path(
            __file__,
        )
        .resolve()
        .parent
        / ".."
        / ".."
        / "staticdata"
    )
    return static_data_path


@pytest.fixture
def load_spacy_model():
    def _load_spacy_model():
        static_data_path = get_staticdata_path()
        model_path = static_data_path / "en_core_web_sm"
        nlp = spacy.load(model_path)
        return nlp

    yield _load_spacy_model

tests/natural_language_processing/test_utils.py

import pytest
from omdenalore.natural_language_processing.utils import TextUtils


@pytest.mark.parametrize(
    "text,expected,exception",
    [
        # No inputs
        (None, None, Exception),
        (
            "This is a sample sentence, showing off the stop words filtration.",
            "This sample sentence, showing stop words filtration.",
            None,
        ),
    ],
)
def test_stop_word_removal(text, expected, exception, monkeypatch, load_spacy_model):

    monkeypatch.setattr(
        TextUtils,
        "_load_spacy_model",
        load_spacy_model,
    )

    if exception:
        with pytest.raises(exception):
            _ = TextUtils.stop_word_removal(input_text=text)
    else:
        result = TextUtils.stop_word_removal(input_text=text)
        assert result == expected

这是我要测试的 class TextUtils。在 stop_word_removal 中,我正在尝试对方法 _load_spacy_model 进行 monkeypatch,该方法用于使用夹具 load_spacy_model.

获取 spacy 模型
class TextUtils:
    """Utility functions for handling text data"""

    @staticmethod
    def _load_spacy_model():
        nlp = spacy.load("en_core_web_sm")
        return nlp

    @staticmethod
    def stop_word_removal(
        input_text: Union[List[str], str],
    ) -> Union[
        List[str], str,
    ]:
        """
        Remove noise from the input text.
        This function can be use to remove common english
        words like "is, a , the".

        :param input_text: Input text to remove stop words from
        :type input_text: str or List[str]
        :returns: Clean text with no noise

        :Example:

        from omdenalore.natural_language_processing.utils import
        TextUtils
        >>> input = "Hello, the chicken crossed the street"
        >>> TextUtils.stop_word_removal(input)
        "Hello, chicken crossed the street"
        """
        nlp = TextUtils._load_spacy_model()
        if isinstance(input_text, list):
            processed_input = []
            for sentence in input_text:
                if isinstance(sentence, str):
                    doc = nlp(sentence)
                    processed_input.append(
                        " ".join([token.text for token in doc if not token.is_stop])
                    )
            return processed_input
        elif isinstance(input_text, str):
            doc = nlp(input_text)
            return " ".join([token.text for token in doc if not token.is_stop])

您正在另一个夹具中直接使用 get_staticdata_path 夹具:load_spacy_model

你试过把它作为固定装置传递吗?

示例:

@pytest.fixture
def load_spacy_model(get_staticdata_path):
    def _load_spacy_model():
        static_data_path = get_staticdata_path
        model_path = static_data_path / "en_core_web_sm"
        nlp = spacy.load(model_path)
        return nlp

    yield _load_spacy_model

查看文档中的这个示例:https://docs.pytest.org/en/6.2.x/fixture.html#back-to-fixtures