1

I am trying to mock a class method that gets called within another class method.

from omdenalore.natural_language_processing.topic_modelling import TopicModelling
from unittest import mock


def test_process_words(load_spacy_model):
    tm = TopicModelling()
    with mock.patch.object(
        TopicModelling.process_words, "TextPreprocessor.load_model", return_value=load_spacy_model
    ):
        processed_words = tm.process_words()
        assert processed_words

TopicModelling class

from omdenalore.natural_language_processing.preprocess_text import (
    TextPreprocessor,
)

class TopicModelling:
    def __init__(self):
        ...
    def process_words(self):
        model = TextPreprocessor.load_model() # trying to mock this 
        # do some stuff with model 

But I keep getting an error AttributeError: <function TopicModelling.process_words at 0x7fb1a2787c20> does not have the attribute 'TextPreprocessor.load_model'.

load_spacy_model is a fixture that I want to patch the function TextPreprocessor.load_model() with.

Similar question which I referred to.

1 Answer 1

3

As I understand your code:

  • you are trying to patch the method TextPreprocessor.load_model, but instead you mock TopicModelling.process_words, and you do so in the namespace under test instead of that where TextPreprocessor.load_model is imported;
  • tm should be instantiated within the with statement, not before it.

So, I would suggest instead the following test script:

from omdenalore.natural_language_processing.topic_modelling import TopicModelling


def test_process_words(mocker):
    # Patch where load_model is called
    process_words = mocker.patch(
        "omdenalore.natural_language_processing.topic_modelling.TextPreprocessor.load_model",
        return_value=load_spacy_model,
    )
    # Instantiate and call
    tm = TopicModelling()
    processed_words = tm.process_words()

    assert processed_words
Sign up to request clarification or add additional context in comments.

1 Comment

I needed to install pytest-mock, then use load_spacy_model() which is a fixture as I previously used it to monkeypatch which needed to yield a function. Now it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.