Reputation: 6799
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.
Upvotes: 1
Views: 2336
Reputation: 13478
As I understand your code:
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
Upvotes: 3