Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix or silence warnings emitted during tests #1501

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
67 commits
Select commit Hold shift + click to select a range
598a1db
Ignore deprecation warnings from gputil
dagardner-nv Dec 19, 2023
0dc1816
Suppress warnings from merlin/nvt regardning tensorflow not being ins…
dagardner-nv Dec 19, 2023
80575ca
Revert "Ignore deprecation warnings from gputil"
dagardner-nv Dec 19, 2023
7a722bb
Ignore distutils deprecation warning
dagardner-nv Dec 19, 2023
0d1fa37
Mark the http server tests as slow
dagardner-nv Dec 19, 2023
da692e8
Capture the warning emitted when timestamp is provided but timestamp …
dagardner-nv Dec 19, 2023
f1dcd44
Narrow the warning filters to be more specific, ensuring we aren't ac…
dagardner-nv Dec 29, 2023
374d6d6
Merge branch 'branch-24.03' of github.com:nv-morpheus/Morpheus into d…
dagardner-nv Dec 29, 2023
42614ec
Silence warnings about not having a config option
dagardner-nv Jan 6, 2024
074081e
Avoid warning from cudf regardning an upcoming change of behavior whe…
dagardner-nv Jan 6, 2024
3a822c7
Add comment explaining the special handling of single element lists
dagardner-nv Jan 6, 2024
3282475
WIP: need to find the root cause of this warning
dagardner-nv Jan 6, 2024
a226c17
Update CR Year
dagardner-nv Jan 8, 2024
907f7d7
Merge branch 'david-pytest-warnings' into david-pytest-warnings-p2
dagardner-nv Jan 8, 2024
a0bbee2
Add comment explaining the warning coming from numpy 1.26
dagardner-nv Jan 8, 2024
62915f5
Merge branch 'branch-24.03' of github.com:nv-morpheus/Morpheus into d…
dagardner-nv Jan 8, 2024
592f7f4
Update test for completion pipe to use actual asyncio futures, simila…
dagardner-nv Jan 9, 2024
032ddec
Avoid warning about setting values on a copy
dagardner-nv Jan 9, 2024
766d474
Ignore performance warnings from pandas triggered by the df compare m…
dagardner-nv Jan 9, 2024
5462726
Restrict numpy to versions prior to 1.25, this avoids numerous warnin…
dagardner-nv Jan 9, 2024
874776f
Silence warning about cudf's subword tokenizer behaving differently t…
dagardner-nv Jan 9, 2024
21d8562
Avoid pandas warning about setting a value on a copy
dagardner-nv Jan 9, 2024
03168a2
Ignore the warning from the logging_timer which happens whenever DFPS…
dagardner-nv Jan 9, 2024
062c214
Fix name of fixture resulting from bad copy/paste
dagardner-nv Jan 11, 2024
a29cece
Replace deprecated usage of is_monotonic attribute with is_monotonic_…
dagardner-nv Jan 11, 2024
5154135
Replace usage of deprecated on_start method in monitor stage
dagardner-nv Jan 11, 2024
e188d3a
Replace usage of deprecated on_start method in HttpServerSinkStage
dagardner-nv Jan 11, 2024
71c7475
Update test to assert that a deprecation warning for on_start is prod…
dagardner-nv Jan 11, 2024
90c79f5
Silence warning regarding tensorflow not being installed from nvt/merlin
dagardner-nv Jan 11, 2024
cb66ea0
avoid deprecation warning about using .astype to convert from a tz-aw…
dagardner-nv Jan 12, 2024
0913d14
Avoid cudf warning that reading a json file uses pandas, create fixtu…
dagardner-nv Jan 12, 2024
07ea3fd
Ignore warning about an existing dask client, as we are explicitly co…
dagardner-nv Jan 12, 2024
b4b1df2
Ignore cudf warnings about Pandas being used under the hood for proce…
dagardner-nv Jan 12, 2024
d88d5ef
Ignore warning that is only produced when calling with an abnormally …
dagardner-nv Jan 12, 2024
45a92e6
Adopt dgl v1.1.1 to pickup pytorch v2.0.1 support. Add rapids-depende…
dagardner-nv Jan 12, 2024
12b71c3
Specify a version for sysroot_linux-64, without this I was getting ou…
dagardner-nv Jan 10, 2024
b5562fa
Switch to using conda to fetch pyarrow-hotfix
dagardner-nv Jan 9, 2024
e07b1c6
Ensure we receive a cuda enabled build of pyarrow
dagardner-nv Jan 12, 2024
82ca88b
update CR
dagardner-nv Jan 12, 2024
95748a4
lint fixes
dagardner-nv Jan 12, 2024
02c74fb
formatting
dagardner-nv Jan 12, 2024
1347cb3
lint fixes
dagardner-nv Jan 12, 2024
6891868
Fix fixture names
dagardner-nv Jan 12, 2024
9d955a6
Merge branch 'branch-24.03' of github.com:nv-morpheus/Morpheus into d…
dagardner-nv Jan 12, 2024
05db11f
Ignore warnings generated by the kafka fixtures themselves, but not t…
dagardner-nv Jan 12, 2024
27c0a18
Fix CR
dagardner-nv Jan 12, 2024
f6eaab4
Don't mock asyncio.gather because it is also used by jinja
dagardner-nv Jan 12, 2024
a973eb2
Set max_batch_size to match model's max_batch_size
dagardner-nv Jan 12, 2024
c7eecae
Update CR
dagardner-nv Jan 12, 2024
0ab58d6
Merge branch 'branch-24.03' into david-pytest-warnings-p2
dagardner-nv Jan 17, 2024
2169ad3
Rename fixture methods to conform to a _fixture suffix
dagardner-nv Jan 17, 2024
4d5b190
Merge branch 'branch-24.03' into david-pytest-warnings-p3
dagardner-nv Feb 7, 2024
7b1c272
Merge branch 'branch-24.03' of github.com:nv-morpheus/Morpheus into d…
dagardner-nv Feb 7, 2024
90d9741
Revert local changes
dagardner-nv Feb 7, 2024
e351772
Ignore deprecation warnings from pyspark
dagardner-nv Feb 7, 2024
0c66850
Fix features value
dagardner-nv Feb 7, 2024
2adb83c
Ignore warning about zero element tensors
dagardner-nv Feb 7, 2024
4e4ca97
Use a list rather than a set for the column names. This allows the re…
dagardner-nv Feb 8, 2024
1ff7adb
Lint fix
dagardner-nv Feb 8, 2024
b8fcbaa
Merge branch 'branch-24.03' of github.com:nv-morpheus/Morpheus into d…
dagardner-nv Feb 8, 2024
76c4f0a
iteritems is deprecated
dagardner-nv Feb 8, 2024
deff7ad
Remove un-needed warning filters
dagardner-nv Feb 8, 2024
2135ea5
Revert uninentional change
dagardner-nv Feb 8, 2024
e1da6d4
Merge branch 'branch-24.03' into david-pytest-warnings-p3
dagardner-nv Feb 8, 2024
2fcb136
Remove warning filter, as newer versions of cudf do not emit this war…
dagardner-nv Feb 12, 2024
01263c1
Merge branch 'branch-24.03' of github.com:nv-morpheus/Morpheus into d…
dagardner-nv Feb 12, 2024
8980297
IWYU fix
dagardner-nv Feb 12, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions examples/llm/vdb_upload/module/content_extractor_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import pandas as pd
from docx import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from pydantic import BaseModel
from pydantic import BaseModel # pylint: disable=no-name-in-module
from pydantic import Field
from pydantic import ValidationError
from pydantic import validator
Expand Down Expand Up @@ -197,7 +197,7 @@ def _csv_to_text_converter(input_info: ConverterInputInfo) -> list[str]:
raise ValueError("The CSV file must either include a 'content' column or have a "
"columns specified in the meta configuration with key 'text_column_names'.")
df.fillna(value='', inplace=True)
text_arr = df[text_column_names].apply(lambda x: ' '.join(map(str, x)), axis=1).tolist()
text_arr = df[sorted(text_column_names)].apply(lambda x: ' '.join(map(str, x)), axis=1).tolist()
return text_arr


Expand Down
2 changes: 1 addition & 1 deletion examples/llm/vdb_upload/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def run():
)
@click.option(
"--model_max_batch_size",
default=64,
default=256,
type=click.IntRange(min=1),
help="Max batch size to use for the model",
)
Expand Down
4 changes: 2 additions & 2 deletions morpheus/_lib/src/objects/table_info.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
#include <pybind11/stl.h> // IWYU pragma: keep

#include <algorithm> // for find, transform
#include <array> // needed for pybind11::make_tuple
#include <cstddef> // for size_t
#include <iterator> // for back_insert_iterator, back_inserter
#include <memory>
Expand Down Expand Up @@ -306,7 +305,8 @@ std::optional<std::string> MutableTableInfo::ensure_sliceable_index()
auto df_index = py_df.attr("index");

// Check to see if we actually need the change
if (df_index.attr("is_unique").cast<bool>() && df_index.attr("is_monotonic").cast<bool>())
if (df_index.attr("is_unique").cast<bool>() && (df_index.attr("is_monotonic_increasing").cast<bool>() ||
df_index.attr("is_monotonic_decreasing").cast<bool>()))
{
// Set the outputname to nullopt
old_index_col_name = std::nullopt;
Expand Down
2 changes: 1 addition & 1 deletion morpheus/controllers/rss_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def _read_file_content(self, file_path: str) -> str:

def _try_parse_feed_with_beautiful_soup(self, feed_input: str) -> "feedparser.FeedParserDict":

soup = BeautifulSoup(feed_input, 'lxml')
soup = BeautifulSoup(feed_input, features='xml')

# Verify whether the given feed has 'item' or 'entry' tags.
if soup.find('item'):
Expand Down
2 changes: 1 addition & 1 deletion morpheus/service/vdb/milvus_vector_db_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ def _build_schema_conf(self, df: typing.Union[cudf.DataFrame, pd.DataFrame]) ->
df = df.to_pandas()

# Loop over all of the columns of the first row and build the schema
for col_name, col_val in df.iloc[0].iteritems():
for col_name, col_val in df.iloc[0].items():

field_dict = {
"name": col_name,
Expand Down
2 changes: 1 addition & 1 deletion morpheus/stages/general/monitor_stage.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def accepted_types(self) -> typing.Tuple:
def supports_cpp_node(self):
return False

def on_start(self):
async def start_async(self):
"""
Starts the pipeline stage's progress bar.
"""
Expand Down
2 changes: 1 addition & 1 deletion morpheus/stages/output/http_server_sink_stage.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def supports_cpp_node(self):
"""Indicates whether or not this stage supports a C++ node."""
return False

def on_start(self):
async def start_async(self):
"""Starts the HTTP server."""
from morpheus.common import HttpServer
self._server = HttpServer(parse_fn=self._request_handler,
Expand Down
9 changes: 8 additions & 1 deletion morpheus/utils/column_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,14 @@ def _process_column(self, df: pd.DataFrame) -> pd.Series:
The processed column as a datetime Series.
"""

return pd.to_datetime(df[self.input_name], infer_datetime_format=True, utc=True).astype(self.get_pandas_dtype())
dt_series = pd.to_datetime(df[self.input_name], infer_datetime_format=True, utc=True)

dtype = self.get_pandas_dtype()
if dtype == 'datetime64[ns]':
# avoid deprecation warning about using .astype to convert from a tz-aware type to a tz-naive type
return dt_series.dt.tz_localize(None)

return dt_series.astype(dtype)


@dataclasses.dataclass
Expand Down
9 changes: 8 additions & 1 deletion morpheus/utils/downloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import os
import threading
import typing
import warnings
from enum import Enum

import fsspec
Expand Down Expand Up @@ -131,7 +132,13 @@ def get_dask_client(self):
dask.config.set({"distributed.client.heartbeat": self._dask_heartbeat_interval})

if (self._merlin_distributed is None):
self._merlin_distributed = Distributed(client=dask.distributed.Client(self.get_dask_cluster()))
with warnings.catch_warnings():
# Merlin.Distributed will warn if a client already exists, the client in question is the one created
# and are explicitly passing to it in the constructor.
warnings.filterwarnings("ignore",
message="Existing Dask-client object detected in the current context.*",
category=UserWarning)
self._merlin_distributed = Distributed(client=dask.distributed.Client(self.get_dask_cluster()))

return self._merlin_distributed

Expand Down
12 changes: 7 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,18 @@ markers = [
]

filterwarnings = [
# Warning coming from mlflow's usage of numpy
'ignore:`np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe',
# Ignore our own warning about the df property since we still have to test it
'ignore:Warning the df property returns a copy, please use the copy_dataframe method or the mutable_dataframe context manager to modify the DataFrame in-place instead.',
'ignore:`np.MachAr` is deprecated \(NumPy 1.22\):DeprecationWarning',
'ignore:Please use `spmatrix` from the `scipy.sparse` namespace, the `scipy.sparse.base` namespace is deprecated:DeprecationWarning',

# Deprecation warning from any project using distutils, currently known sources of this are:
# GPUtils https://github.com/anderskm/gputil/issues/48
# PySpark https://issues.apache.org/jira/browse/SPARK-45390
# PySpark https://issues.apache.org/jira/browse/SPARK-45390 & https://issues.apache.org/jira/browse/SPARK-38660
'ignore:The distutils package is deprecated and slated for removal in Python 3.12. Use setuptools or check PEP 632 for potential alternatives',
'ignore:distutils Version classes are deprecated. Use packaging.version instead.',

# Ignore cudf warnings about Pandas being used under the hood for processing json
'ignore:Using CPU via Pandas to write JSON dataset',
'ignore:Using CPU via Pandas to read JSON dataset',
]

testpaths = ["tests"]
Expand Down
6 changes: 5 additions & 1 deletion tests/_utils/dataset_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import os
import random
import typing
import warnings

import cupy as cp
import pandas as pd
Expand Down Expand Up @@ -235,7 +236,10 @@ def compare_df(cls,
dfb: typing.Union[pd.DataFrame, cdf.DataFrame],
**compare_args):
"""Wrapper for `morpheus.utils.compare_df.compare_df`."""
return compare_df.compare_df(cls._value_as_pandas(dfa), cls._value_as_pandas(dfb), **compare_args)
with warnings.catch_warnings():
# Ignore performance warnings from pandas triggered by the comparison
warnings.filterwarnings("ignore", category=pd.errors.PerformanceWarning)
return compare_df.compare_df(cls._value_as_pandas(dfa), cls._value_as_pandas(dfb), **compare_args)

@classmethod
def assert_compare_df(cls,
Expand Down
14 changes: 10 additions & 4 deletions tests/_utils/kafka.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import subprocess
import time
import typing
import warnings
from collections import namedtuple
from functools import partial

Expand Down Expand Up @@ -73,10 +74,15 @@ def seek_to_beginning(kafka_consumer: "KafkaConsumer", timeout: int = PARTITION_

@pytest.fixture(name='kafka_consumer', scope='function')
def kafka_consumer_fixture(kafka_topics: KafkaTopics, _kafka_consumer: "KafkaConsumer"):
_kafka_consumer.subscribe([kafka_topics.output_topic])
seek_to_beginning(_kafka_consumer)

yield _kafka_consumer
with warnings.catch_warnings():
# Ignore warnings specific to the test fixture and not the actual morpheus code
warnings.filterwarnings("ignore",
message=r"Exception ignored in:.*ConsumerCoordinator\.__del__",
category=pytest.PytestUnraisableExceptionWarning)
_kafka_consumer.subscribe([kafka_topics.output_topic])
seek_to_beginning(_kafka_consumer)

yield _kafka_consumer


def _init_pytest_kafka() -> (bool, Exception):
Expand Down
6 changes: 5 additions & 1 deletion tests/dfencoder/test_autoencoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import os
import typing
import warnings
from unittest.mock import patch

import numpy as np
Expand Down Expand Up @@ -493,7 +494,10 @@ def test_auto_encoder_num_only_convergence(train_ae: autoencoder.AutoEncoder):
'num_feat_2': [3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1],
})

train_ae.fit(num_df, epochs=50)
with warnings.catch_warnings():
# Ignore warning regarding tensorflow not being installed
warnings.filterwarnings("ignore", message="Initializing zero-element tensors is a no-op", category=UserWarning)
train_ae.fit(num_df, epochs=50)

avg_loss = np.sum([np.array(loss[1])
for loss in train_ae.logger.train_fts.values()], axis=0) / len(train_ae.logger.train_fts)
Expand Down
38 changes: 22 additions & 16 deletions tests/dfencoder/test_scalers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import warnings

import numpy as np
import pytest
import torch
Expand All @@ -25,35 +27,41 @@
# pylint: disable=redefined-outer-name


@pytest.fixture(scope="function")
def fit_tensor():
@pytest.fixture(name="fit_tensor", scope="function")
def fit_tensor_fixture():
yield torch.tensor([4.4, 5.3, 6.5], dtype=torch.float32)


@pytest.fixture(scope="function")
def tensor():
@pytest.fixture(name="tensor", scope="function")
def tensor_fixture():
yield torch.tensor([7.4, 8.3, 9.5], dtype=torch.float32)


@pytest.fixture(scope="function")
def standard_scaler(fit_tensor):
@pytest.fixture(name="standard_scaler", scope="function")
def standard_scaler_fixture(fit_tensor):
scaler = scalers.StandardScaler()
scaler.fit(fit_tensor)
yield scaler


@pytest.fixture(scope="function")
def modified_scaler(fit_tensor):
@pytest.fixture(name="modified_scaler", scope="function")
def modified_scaler_fixture(fit_tensor):
scaler = scalers.ModifiedScaler()
scaler.fit(fit_tensor)
yield scaler


@pytest.fixture(scope="function")
def gauss_rank_scaler(fit_tensor):
@pytest.fixture(name="gauss_rank_scaler", scope="function")
def gauss_rank_scaler_fixture(fit_tensor):
scaler = scalers.GaussRankScaler()
scaler.fit(fit_tensor)
yield scaler

with warnings.catch_warnings():
# This warning is triggered by the abnormally small tensor size used in this test
warnings.filterwarnings("ignore",
message=r"n_quantiles \(1000\) is greater than the total number of samples \(3\).*",
category=UserWarning)
scaler.fit(fit_tensor)
yield scaler


def test_ensure_float_type():
Expand Down Expand Up @@ -111,8 +119,7 @@ def test_modified_scaler_transform(modified_scaler, tensor):
assert torch.equal(torch.round(results, decimals=2), expected), f"{results} != {expected}"

# Test alternate path where median absolute deviation is 1
test = torch.tensor([3.0, 4.0, 4.0, 5.0])
modified_scaler.fit(test)
modified_scaler.fit(torch.tensor([3.0, 4.0, 4.0, 5.0]))
results = modified_scaler.transform(tensor)
expected = torch.tensor([5.43, 6.86, 8.78])
assert torch.equal(torch.round(results, decimals=2), expected), f"{results} != {expected}"
Expand All @@ -124,8 +131,7 @@ def test_modified_scaler_inverse_transform(modified_scaler, tensor):
assert torch.equal(torch.round(results, decimals=2), expected), f"{results} != {expected}"

# Test alternate path where median absolute deviation is 1
test = torch.tensor([3.0, 4.0, 4.0, 5.0])
modified_scaler.fit(test)
modified_scaler.fit(torch.tensor([3.0, 4.0, 4.0, 5.0]))
results = modified_scaler.inverse_transform(tensor)
expected = torch.tensor([8.64, 9.2, 9.95])
assert torch.equal(torch.round(results, decimals=2), expected), f"{results} != {expected}"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def test_process_events_on_data(mock_datetime: mock.MagicMock,

# post-process should replace nans, lets add a nan to the DF
with dfp_multi_ae_message.meta.mutable_dataframe() as df:
df['v2'][10] = np.nan
df.loc[10, 'v2'] = np.nan
df['event_time'] = ''

set_log_level(morpheus_log_level)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import json
import os
import typing
import warnings

import pytest

Expand Down Expand Up @@ -99,7 +100,12 @@ def test_extract_users(config: Config,
skip_users=skip_users,
only_users=only_users)

results = stage.extract_users(df)
with warnings.catch_warnings():
# Ignore warning about the log message not being set. This happens whenever there aren't any output_messages
warnings.filterwarnings("ignore",
message="Must set log msg before end of context! Skipping log",
category=UserWarning)
results = stage.extract_users(df)

if not include_generic and not include_individual:
# Extra check for weird combination
Expand Down
6 changes: 3 additions & 3 deletions tests/examples/llm/common/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,10 @@ def import_content_extractor_module(restore_sys_path): # pylint: disable=unused
return content_extractor_module


@pytest.fixture(name="nemollm", autouse=True, scope='session')
def nemollm_fixture(fail_missing: bool):
@pytest.fixture(name="langchain", autouse=True, scope='session')
def langchain_fixture(fail_missing: bool):
"""
All the tests in this subdir require nemollm
All the tests in this subdir require langchain
"""

skip_reason = ("Tests for the WebScraperStage require the langchain package to be installed, to install this run:\n"
Expand Down
6 changes: 3 additions & 3 deletions tests/examples/ransomware_detection/test_preprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,10 @@ def test_merge_curr_and_prev_snapshots(self, config: Config, rwd_conf: dict, dat
}

expected_df = dataset_pandas['examples/ransomware_detection/dask_results.csv'].fillna('')
expected_df['pid_process'][1] = 'test_val1'
expected_df['pid_process'][3] = 'test_val2'
expected_df.loc[1, 'pid_process'] = 'test_val1'
expected_df.loc[3, 'pid_process'] = 'test_val2'

expected_df['snapshot_id'] = snapshot_ids
expected_df.loc[:, 'snapshot_id'] = snapshot_ids
expected_df.index = expected_df.snapshot_id

stage._merge_curr_and_prev_snapshots(df, source_pid_process)
Expand Down
23 changes: 23 additions & 0 deletions tests/llm/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
import typing
from unittest import mock

import pytest

from _utils import require_env_variable
Expand Down Expand Up @@ -94,3 +98,22 @@ def serpapi_api_key_fixture():
yield require_env_variable(
varname="SERPAPI_API_KEY",
reason="serpapi integration tests require the `SERPAPI_API_KEY` environment variable to be defined.")


@pytest.mark.usefixtures("nemollm")
@pytest.fixture(name="mock_nemollm")
def mock_nemollm_fixture(mock_nemollm: mock.MagicMock):

# The generate function is a blocking call that returns a future when return_type="async"
async def mock_task(fut: asyncio.Future, value: typing.Any = mock.DEFAULT):
fut.set_result(value)

def create_future(*args, **kwargs) -> asyncio.Future: # pylint: disable=unused-argument
event_loop = asyncio.get_event_loop()
fut = event_loop.create_future()
event_loop.create_task(mock_task(fut, mock.DEFAULT))
return fut

mock_nemollm.generate.side_effect = create_future

yield mock_nemollm
Loading
Loading