repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
mlflow
tests/spark/autologging/ml/test_pyspark_ml_autologging_custom_allowlist.py
.py
import os from pyspark.sql import SparkSession import mlflow # Put this test in separate module because it require a spark context # with a special conf and the conf is immutable in runtime. def test_custom_log_model_allowlist(tmp_path): allowlist_file_path = os.path.join(tmp_path, "allowlist") with open(al...
88
3,808
mlflow
tests/spark/autologging/ml/test_pyspark_ml_autologging.py
.py
import importlib import json import math import pathlib from typing import Any, NamedTuple from unittest import mock import numpy as np import pandas as pd import pyspark import pytest import yaml from packaging.version import Version from pyspark.ml import Pipeline from pyspark.ml.classification import ( LinearSV...
1,351
52,120
mlflow
tests/pyfunc/test_backward_compatibility.py
.py
import pytest import mlflow @pytest.mark.parametrize("version", ["2.7.1", "2.8.1"]) def test_backward_compatibility(version): model = mlflow.pyfunc.load_model(f"tests/resources/pyfunc_models/{version}") assert model.predict("MLflow is great!") == "MLflow is great!"
10
277
mlflow
tests/pyfunc/test_dependencies_functions.py
.py
from pathlib import Path from unittest import mock import pytest import sklearn from sklearn.linear_model import LinearRegression import mlflow.utils.requirements_utils from mlflow.exceptions import MlflowException from mlflow.pyfunc import get_model_dependencies from mlflow.utils import PYTHON_VERSION def test_get...
140
4,313
mlflow
tests/pyfunc/test_pyfunc_model_with_type_hints.py
.py
import datetime import json import os import subprocess import sys from typing import Any, Dict, List, NamedTuple, Optional, Union from unittest import mock import pandas as pd import pydantic import pytest from pyspark.sql import SparkSession from pyspark.sql.types import ( ArrayType, IntegerType, MapType...
1,153
42,741
mlflow
tests/pyfunc/utils.py
.py
import json import os from typing import TYPE_CHECKING from fastapi.testclient import TestClient import mlflow from mlflow.pyfunc import scoring_server if TYPE_CHECKING: import httpx def score_model_in_process(model_uri: str, data: str, content_type: str) -> "httpx.Response": """Score a model using in-proc...
40
1,381
mlflow
tests/pyfunc/test_chat_agent.py
.py
import json from typing import Any from uuid import uuid4 import pydantic import pytest import mlflow from mlflow.exceptions import MlflowException from mlflow.models.model import Model from mlflow.models.signature import ModelSignature from mlflow.models.utils import load_serving_example from mlflow.pyfunc.loaders.c...
471
17,282
mlflow
tests/pyfunc/test_pyfunc_input_converter.py
.py
from dataclasses import asdict, dataclass from typing import Optional import pandas as pd import pytest from mlflow.models.rag_signatures import ChatCompletionRequest from mlflow.pyfunc.utils.input_converter import _hydrate_dataclass def test_hydrate_dataclass_input_no_dataclass(): # Define a class that is not ...
90
2,529
mlflow
tests/pyfunc/test_model_export_with_loader_module_and_data_path.py
.py
import os import pickle import types from unittest import mock import cloudpickle import numpy as np import pytest import sklearn.datasets import sklearn.neighbors import yaml import mlflow import mlflow.pyfunc from mlflow.exceptions import MlflowException from mlflow.models import Model, infer_signature from mlflow....
369
12,659
mlflow
tests/pyfunc/test_virtualenv.py
.py
import os import sys from io import BytesIO from stat import S_IRGRP, S_IROTH, S_IRUSR, S_IXGRP, S_IXOTH, S_IXUSR from typing import NamedTuple import numpy as np import pandas as pd import pytest import sklearn from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression import mlflow f...
232
8,129
mlflow
tests/pyfunc/test_pyfunc_class_methods.py
.py
import mlflow from mlflow.pyfunc import PythonModel, load_model, log_model def test_unwrap_python_model_from_pyfunc_class(): class MyModel(PythonModel): def __init__(self, param_1: str, param_2: int): self.param_1 = param_1 self.param_2 = param_2 def predict(self, context,...
26
958
mlflow
tests/pyfunc/test_pyfunc_exceptions.py
.py
import pytest import mlflow from mlflow.exceptions import MlflowException class UnpicklableModel(mlflow.pyfunc.PythonModel): def __init__(self, path): with open(path, "w+") as f: pass self.not_a_file = f def test_pyfunc_unpicklable_exception(tmp_path): model = UnpicklableModel(...
23
579
mlflow
tests/pyfunc/test_inferred_code_path.py
.py
import os import pickle import numpy as np import pytest import sklearn.datasets import sklearn.neighbors import mlflow from mlflow.models import Model @pytest.fixture def model_path(tmp_path): return tmp_path / "model" @pytest.fixture(scope="module") def iris_data(): iris = sklearn.datasets.load_iris() ...
150
4,553
mlflow
tests/pyfunc/test_pyfunc_schema_enforcement_pyspark.py
.py
from datetime import datetime import pytest from pyspark.sql import Row, SparkSession from pyspark.sql.types import ( ArrayType, BinaryType, BooleanType, DateType, DoubleType, FloatType, IntegerType, LongType, ShortType, StringType, StructField, StructType, Timestamp...
338
10,510
mlflow
tests/pyfunc/test_spark.py
.py
import datetime import os import random import shutil import subprocess import sys import threading import time from pathlib import Path from typing import Any, Iterator, NamedTuple from unittest import mock import cloudpickle import numpy as np import pandas as pd import pyspark import pytest from packaging.version i...
1,779
64,229
mlflow
tests/pyfunc/test_responses_agent_validation.py
.py
import pytest from pydantic import ValidationError from mlflow.types.responses import ( ResponsesAgentRequest, ResponsesAgentResponse, ResponsesAgentStreamEvent, responses_to_cc, to_chat_completions_input, ) from mlflow.types.responses_helpers import FunctionCallOutput, Message def test_responses...
233
7,521
mlflow
tests/pyfunc/test_uv_model_logging.py
.py
import platform import shutil import subprocess import sys from pathlib import Path from unittest import mock import pytest import mlflow import mlflow.pyfunc from mlflow.utils.os import is_windows from mlflow.utils.uv_utils import ( _PYPROJECT_FILE, _PYTHON_VERSION_FILE, _UV_LOCK_FILE, is_uv_availabl...
504
16,338
mlflow
tests/pyfunc/test_scoring_server.py
.py
import json import math import os import random import signal from io import BytesIO, StringIO from typing import Any, NamedTuple import keras import numpy as np import pandas as pd import pydantic import pytest import sklearn.linear_model as logreg_module from packaging.version import Version from sklearn import data...
1,133
41,049
mlflow
tests/pyfunc/test_logged_models.py
.py
import json import os from concurrent.futures import ThreadPoolExecutor import pytest import mlflow from mlflow.entities.logged_model_status import LoggedModelStatus from mlflow.exceptions import MlflowException from mlflow.models import Model from mlflow.tracing.constant import TraceMetadataKey from mlflow.utils.mlf...
158
6,171
mlflow
tests/pyfunc/test_responses_agent.py
.py
import functools import pathlib import pickle from typing import Generator from uuid import uuid4 import pytest import mlflow from mlflow.entities.span import SpanType from mlflow.exceptions import MlflowException from mlflow.models.signature import ModelSignature from mlflow.pyfunc.loaders.responses_agent import _Re...
1,491
56,626
mlflow
tests/pyfunc/test_model_export_with_class_and_artifacts.py
.py
from __future__ import annotations import importlib.metadata import json import ntpath import os import subprocess import sys import types import uuid from pathlib import Path from subprocess import PIPE, Popen from typing import Any, Dict, List from unittest import mock import cloudpickle import numpy as np import p...
2,948
110,389
mlflow
tests/pyfunc/test_spark_connect.py
.py
import numpy as np import pandas as pd import pytest from pyspark.sql import SparkSession from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression import mlflow @pytest.fixture(scope="module") def spark(): spark = SparkSession.builder.remote("local[2]").getOrCreate() yield s...
53
1,932
mlflow
tests/pyfunc/test_chat_model_validation.py
.py
import pytest from mlflow.types.llm import ( ChatChoice, ChatCompletionRequest, ChatCompletionResponse, ChatMessage, TokenUsageStats, ) MOCK_RESPONSE = { "id": "123", "object": "chat.completion", "created": 1677652288, "model": "MyChatModel", "choices": [ { ...
274
8,477
mlflow
tests/pyfunc/test_context.py
.py
import random import time from threading import Thread import pytest import mlflow from mlflow.pyfunc.context import ( Context, get_prediction_context, set_prediction_context, ) def test_prediction_context_thread_safe(): def set_context(context): with set_prediction_context(context): ...
67
2,150
mlflow
tests/pyfunc/test_chat_model.py
.py
import json import pathlib import pickle import uuid from dataclasses import asdict import pytest import mlflow from mlflow.exceptions import MlflowException from mlflow.models.model import Model from mlflow.models.signature import ModelSignature from mlflow.models.utils import load_serving_example from mlflow.pyfunc...
662
21,901
mlflow
tests/pyfunc/test_pyfunc_schema_enforcement.py
.py
import base64 import datetime import decimal import json import os import re from unittest import mock import cloudpickle import numpy as np import pandas as pd import pytest import sklearn.linear_model from packaging.version import Version import mlflow import mlflow.pyfunc.scoring_server as pyfunc_scoring_server fr...
3,084
119,325
mlflow
tests/pyfunc/test_pyfunc_model_config.py
.py
import os import pytest import yaml import mlflow from mlflow.models import Model @pytest.fixture def model_path(tmp_path): return os.path.join(tmp_path, "model") @pytest.fixture def model_config(): return { "use_gpu": True, "temperature": 0.9, "timeout": 300, } def _load_pyf...
155
5,259
mlflow
tests/pyfunc/test_rag_model.py
.py
import json from dataclasses import asdict import mlflow from mlflow.models.model import Model from mlflow.models.rag_signatures import ( ChainCompletionChoice, ChatCompletionRequest, ChatCompletionResponse, Message, ) from mlflow.models.signature import ModelSignature from tests.helper_functions impo...
60
2,145
mlflow
tests/pyfunc/test_chat_agent_validation.py
.py
import pytest from mlflow.types.agent import ChatAgentChunk, ChatAgentMessage, ChatAgentResponse def test_chat_agent_message_throws_on_invalid_data(): # Missing 'content' or 'tool_calls' data = {"role": "user", "name": "test_user"} with pytest.raises(ValueError, match="Either 'content' or 'tool_calls'"):...
79
2,893
mlflow
tests/pyfunc/docker/test_docker_flavors.py
.py
import contextlib import os import shutil import sys import threading import time import pandas as pd import pytest import requests import mlflow from mlflow.environment_variables import _MLFLOW_RUN_SLOW_TESTS from mlflow.models.flavor_backend_registry import get_flavor_backend from mlflow.models.utils import load_se...
405
11,951
mlflow
tests/pyfunc/docker/test_docker.py
.py
import difflib import os import shutil from dataclasses import dataclass from pathlib import Path from unittest import mock import pytest import sklearn import sklearn.neighbors from packaging.version import Version import mlflow from mlflow.environment_variables import _MLFLOW_RUN_SLOW_TESTS from mlflow.models impor...
158
5,415
mlflow
tests/pyfunc/docker/conftest.py
.py
import logging import os import subprocess from functools import lru_cache import docker import pytest import requests from packaging.version import Version import mlflow TEST_IMAGE_NAME = "test_image" MLFLOW_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..")) RESOURCE_DIR = os.path.joi...
79
2,734
mlflow
tests/pyfunc/custom_model/loader.py
.py
import pickle from custom_model.mod1 import mod2 __all__ = ["mod2"] def _load_pyfunc(path): with open(path, "rb") as f: return pickle.load(f, encoding="latin1")
11
177
mlflow
tests/pyfunc/custom_model/transitive_test/transitive_dependency.py
.py
def some_function(): return "test"
3
39
mlflow
tests/pyfunc/custom_model/transitive_test/model_with_transitive.py
.py
from custom_model.transitive_test.transitive_dependency import some_function from mlflow.pyfunc import PythonModel class ModelWithTransitiveDependency(PythonModel): def predict(self, context, model_input, params=None): result = some_function() return [result] * len(model_input)
10
302
mlflow
tests/pyfunc/custom_model/mod1/__init__.py
.py
from . import mod2 # noqa __all__ = ["mod2"]
4
47
mlflow
tests/pyfunc/custom_model/mod1/mod4.py
.py
# The 2 importing commands are for testing these imported library # code files won't be captured by `infer_code_paths=True` import scipy import sklearn sk_version = sklearn.__version__ scipy_version = scipy.__version__
8
220
mlflow
tests/pyfunc/custom_model/mod1/mod2/__init__.py
.py
from .. import mod4 # noqa __all__ = ["mod4"]
4
48
mlflow
tests/pyfunc/sample_code/python_model_with_config.py
.py
from mlflow.models import ModelConfig, set_model from mlflow.pyfunc import PythonModel base_config = ModelConfig(development_config="tests/pyfunc/sample_code/config.yml") class MyModel(PythonModel): def predict(self, context, model_input): timeout = base_config.get("timeout") return f"Predict cal...
14
392
mlflow
tests/pyfunc/sample_code/python_model.py
.py
from mlflow.models import set_model from mlflow.pyfunc import PythonModel class MyModel(PythonModel): def predict(self, context, model_input): return f"This was the input: {model_input}" set_model(MyModel())
11
224
mlflow
tests/pyfunc/sample_code/utils.py
.py
def my_function(input): return f"My utils function received this input: {input}"
3
85
mlflow
tests/pyfunc/sample_code/func_code_with_type_hint.py
.py
from mlflow.models import set_model def predict(model_input: list[str]): return model_input set_model(predict)
9
119
mlflow
tests/pyfunc/sample_code/python_model_with_utils.py
.py
from mlflow.models import set_model from mlflow.pyfunc import PythonModel class MyModel(PythonModel): def predict(self, context, model_input): from utils import my_function return my_function(model_input) set_model(MyModel())
13
251
mlflow
tests/pyfunc/sample_code/func_code.py
.py
from mlflow.models import set_model def predict(model_input): return model_input set_model(predict)
9
108
mlflow
tests/pyfunc/sample_code/streamable_model_code.py
.py
from mlflow.models import set_model from mlflow.pyfunc import PythonModel class StreamableModel(PythonModel): def __init__(self): pass def predict(self, context, model_input, params=None): pass def predict_stream(self, context, model_input, params=None): yield "test1" yie...
18
362
mlflow
tests/pyfunc/sample_code/func_code_with_config.py
.py
from mlflow.models import ModelConfig, set_model def predict(model_input: list[str]): model_config = ModelConfig(development_config="tests/pyfunc/sample_code/config.yml") timeout = model_config.get("timeout") return f"This was the input: {model_input[0]}, timeout {timeout}" set_model(predict)
11
310
mlflow
tests/pyfunc/sample_code/code_with_dependencies.py
.py
import os import mlflow from mlflow.models import set_model, set_retriever_schema from mlflow.pyfunc import PythonModel test_trace = os.environ.get("TEST_TRACE", "true").lower() == "true" class MyModel(PythonModel): def _call_retriever(self, id): return f"Retriever called with ID: {id}. Output: 42." ...
42
1,241
mlflow
tests/ai_commands/test_ai_command_utils.py
.py
import platform from unittest import mock import pytest from mlflow.ai_commands import get_command, get_command_body, list_commands, parse_frontmatter def test_parse_frontmatter_with_metadata(): content = """--- namespace: genai description: Test command --- # Command content This is the body.""" metadata...
283
7,863
mlflow
tests/openai/test_openai_model_export.py
.py
import importlib import json from unittest import mock import numpy as np import openai import pandas as pd import pytest import yaml from pyspark.sql import SparkSession import mlflow import mlflow.pyfunc.scoring_server as pyfunc_scoring_server from mlflow.models.signature import ModelSignature from mlflow.models.ut...
707
21,151
mlflow
tests/openai/mock_openai.py
.py
import argparse import base64 import json from typing import Any import fastapi from pydantic import BaseModel from starlette.responses import StreamingResponse from mlflow.types.chat import ChatCompletionRequest EMPTY_CHOICES = "EMPTY_CHOICES" LIST_CONTENT = "LIST_CONTENT" AZURE_ANNOTATIONS = "AZURE_ANNOTATIONS" a...
548
15,860
mlflow
tests/openai/test_openai_evaluate.py
.py
from unittest import mock import openai import pandas as pd import pytest import mlflow from mlflow.models.evaluation import evaluate from mlflow.tracing.constant import TraceMetadataKey from tests.tracing.helper import get_traces, purge_traces, reset_autolog_state # noqa: F401 _EVAL_DATA = pd.DataFrame({ "inp...
138
3,999
mlflow
tests/openai/test_openai_responses_autolog.py
.py
from unittest import mock import httpx import openai import pytest from packaging.version import Version import mlflow from mlflow.entities.span import SpanType from mlflow.tracing.constant import SpanAttributeKey, TokenUsageKey from tests.tracing.helper import get_traces if Version(openai.__version__) < Version("1...
384
11,536
mlflow
tests/openai/test_genai_semconv_converter.py
.py
import importlib.metadata import json import openai import pytest from packaging.version import Version import mlflow from mlflow.openai.genai_semconv_converter import _convert_content, _convert_message from tests.tracing.helper import capture_otel_export, reset_autolog_state # noqa: F401 MODEL = "gpt-4o-mini" _o...
316
11,080
mlflow
tests/openai/test_openai_autolog.py
.py
import json import re import sys from unittest import mock import httpx import openai import pytest from openai.resources.chat.completions import Completions as ChatCompletions from openai.resources.completions import Completions from openai.resources.embeddings import Embeddings from packaging.version import Version ...
1,295
44,527
mlflow
tests/openai/test_openai_agent_autolog.py
.py
import asyncio import copy import gc import json from unittest import mock import openai import pytest try: import agents # noqa: F401 except ImportError: pytest.skip("OpenAI SDK is not installed. Skipping tests.", allow_module_level=True) from agents import Agent, Runner, function_tool, set_default_openai_...
646
20,725
mlflow
tests/openai/conftest.py
.py
import importlib.metadata import pytest from packaging.version import Version from tests.helper_functions import start_mock_openai_server is_v1 = Version(importlib.metadata.version("openai")).major >= 1 @pytest.fixture(scope="module", autouse=True) def mock_openai(): with start_mock_openai_server() as base_url...
15
345
mlflow
tests/anthropic/test_anthropic_autolog.py
.py
import asyncio import re from typing import Any from unittest.mock import ANY, patch import anthropic import pytest from anthropic.types import Message, TextBlock, ToolUseBlock, Usage import mlflow.anthropic from mlflow.entities import SpanLogLevel from mlflow.entities.span import SpanType from mlflow.tracing.constan...
499
16,785
mlflow
tests/anthropic/test_anthropic_genai_semconv_converter.py
.py
import json from unittest.mock import patch import anthropic import pytest from packaging.version import Version import mlflow from mlflow.anthropic.genai_semconv_converter import _convert_block from mlflow.tracing.constant import GenAiSemconvKey from tests.anthropic.test_anthropic_autolog import ( DUMMY_CREATE_...
177
6,463
mlflow
tests/sentence_transformers/test_sentence_transformers_model_export.py
.py
import json import os from unittest import mock import numpy as np import pandas as pd import pytest import sentence_transformers import yaml from packaging.version import Version from pyspark.sql import SparkSession from pyspark.sql.types import ArrayType, DoubleType from sentence_transformers import SentenceTransfor...
599
22,983
mlflow
tests/optuna/test_storage.py
.py
import gc import random import threading import time from datetime import datetime from time import sleep from typing import Any from unittest.mock import MagicMock, call, patch import numpy as np import pytest from optuna.distributions import CategoricalDistribution, FloatDistribution from optuna.storages import Base...
727
28,494
mlflow
tests/metrics/test_metric_base.py
.py
from mlflow.metrics.base import MetricValue def test_metric_value(): metricValue1 = MetricValue( scores=[1, 2, 3], justifications=["foo", "bar", "baz"], aggregate_results={"mean": 2}, ) metricValue2 = MetricValue( scores=[1, 2, 3], justifications=["foo", "bar", "ba...
39
1,144
mlflow
tests/metrics/test_metric_definitions.py
.py
import inspect import io import sys from unittest import mock import pandas as pd import pytest from mlflow.metrics import ( MetricValue, ari_grade_level, bleu, exact_match, f1_score, flesch_kincaid_grade_level, mae, mape, max_error, mse, ndcg_at_k, precision_at_k, ...
396
14,379
mlflow
tests/metrics/genai/test_model_utils.py
.py
import copy import json import sys from unittest import mock import pytest import requests from mlflow.exceptions import MlflowException from mlflow.genai.utils.gateway_utils import GatewayConfig from mlflow.metrics.genai import model_utils from mlflow.metrics.genai.model_utils import ( _MODELS_WITHOUT_OUTPUT_CON...
842
29,498
mlflow
tests/metrics/genai/test_base.py
.py
import re from mlflow.metrics.genai import EvaluationExample def test_evaluation_example_str(): example1 = str( EvaluationExample( input="This is an input", output="This is an output", score=5, justification="This is a justification", grading_co...
73
1,827
mlflow
tests/metrics/genai/test_prompt_template.py
.py
from mlflow.metrics.genai.prompt_template import PromptTemplate def test_prompt_template_flat_str_no_variables(): prompt = PromptTemplate(template_str="Say {foo}") assert prompt.format(foo="bar") == "Say bar" prompt = PromptTemplate(template_str="Say {foo} {baz}") assert prompt.format(foo="bar") == "...
58
2,228
mlflow
tests/metrics/genai/test_genai_metrics.py
.py
import inspect import re from unittest import mock import numpy as np import pandas as pd import pytest from mlflow.exceptions import MlflowException from mlflow.metrics.genai import EvaluationExample, model_utils from mlflow.metrics.genai.genai_metric import ( _extract_score_and_justification, _format_args_s...
1,389
60,220
mlflow
tests/metrics/genai/prompts/test_v1.py
.py
import re import pytest from mlflow.metrics.genai import EvaluationExample from mlflow.metrics.genai.prompts.v1 import EvaluationModel def test_evaluation_model_output(): model1 = EvaluationModel( name="correctness", definition="Correctness refers to how well the generated output matches " ...
267
11,367
mlflow
tests/mcp/test_mcp.py
.py
import sys from collections.abc import AsyncIterator from unittest.mock import patch import click import pytest import pytest_asyncio from fastmcp import Client from fastmcp.client.transports import StdioTransport import mlflow from mlflow.mcp import server from mlflow.mcp.server import fn_wrapper from mlflow.models ...
214
6,307
mlflow
tests/mcp/test_cli.py
.py
import sys import pytest from fastmcp import Client from fastmcp.client.transports import StdioTransport import mlflow @pytest.mark.asyncio async def test_cli(): transport = StdioTransport( command=sys.executable, args=[ "-m", "mlflow", "mcp", "run...
28
593
mlflow
tests/utils/test_semver_utils.py
.py
from functools import cmp_to_key from itertools import product import pytest from mlflow.exceptions import MlflowException from mlflow.utils.semver_utils import ( SemVer, compare_semver, encode_prerelease_sort_key, parse_semver, ) def _compare_identifiers(left: str, right: str) -> int: left_is_n...
393
11,273
mlflow
tests/utils/test_server_info.py
.py
import os import select import signal import threading from unittest import mock import pytest from mlflow.utils import server_info from mlflow.utils.rest_utils import MlflowHostCreds from mlflow.utils.server_info import ( SERVER_INFO_ENDPOINT, ServerInfoRequestError, ServerInfoResponse, _clear_server...
570
19,117
mlflow
tests/utils/test_providers.py
.py
import json from unittest import mock import pytest from mlflow.exceptions import MlflowException from mlflow.utils.providers import ( _fetch_remote_provider, _flatten_catalog_entry, _get_remote_cache, _list_provider_names, _load_bundled_provider, _load_provider, _normalize_provider, c...
571
20,028
mlflow
tests/utils/test_exception.py
.py
import json from mlflow.exceptions import ExecutionException, RestException from mlflow.protos.databricks_pb2 import RESOURCE_DOES_NOT_EXIST, ErrorCode def test_execution_exception_string_repr(): exc = ExecutionException("Uh oh") assert str(exc) == "Uh oh" json.loads(exc.serialize_as_json()) def test_r...
40
1,246
mlflow
tests/utils/test_search_utils.py
.py
import base64 import json import re import pytest from mlflow.entities import ( Dataset, DatasetInput, InputTag, LifecycleStage, Metric, Param, Run, RunData, RunInfo, RunInputs, RunStatus, RunTag, TraceState, trace_location, ) from mlflow.entities.trace_info imp...
894
32,647
mlflow
tests/utils/test_class_utils.py
.py
import mlflow from mlflow.utils.class_utils import _get_class_from_string def test_get_class_from_string(): assert _get_class_from_string("mlflow.MlflowClient") == mlflow.MlflowClient
7
190
mlflow
tests/utils/test_file_utils.py
.py
import filecmp import hashlib import io import os import shutil import stat import tarfile from pathlib import Path import pytest from pyspark.sql import SparkSession import mlflow from mlflow.exceptions import MlflowException from mlflow.pyfunc.dbconnect_artifact_cache import extract_archive_to_dir from mlflow.utils...
393
14,825
mlflow
tests/utils/test_promptlab_utils.py
.py
import json import os import pytest from mlflow.entities.param import Param from mlflow.entities.run_status import RunStatus from mlflow.store.artifact.artifact_repository_registry import get_artifact_repository from mlflow.tracking._tracking_service.utils import _get_store from mlflow.utils.promptlab_utils import ( ...
104
3,581
mlflow
tests/utils/test_oss_registry_utils.py
.py
from unittest import mock import pytest from mlflow.exceptions import MlflowException from mlflow.utils.oss_registry_utils import get_oss_host_creds from mlflow.utils.rest_utils import MlflowHostCreds @pytest.mark.parametrize( ("server_uri", "expected_creds"), [ ("uc:databricks-uc", MlflowHostCreds(...
42
1,546
mlflow
tests/utils/test_thread_utils.py
.py
import contextvars from concurrent.futures import ThreadPoolExecutor import pytest from mlflow.utils.thread_utils import map_with_context _TEST_CTX = contextvars.ContextVar("test_ctx", default=None) def test_map_with_context_propagates_caller_context(): _TEST_CTX.set("caller-value") def worker(_): ...
67
1,948
mlflow
tests/utils/test_model_utils.py
.py
import os import sys from unittest import mock import pytest import sklearn.linear_model as logreg_module from sklearn import datasets import mlflow.sklearn import mlflow.utils.model_utils as mlflow_model_utils from mlflow.environment_variables import MLFLOW_RECORD_ENV_VARS_IN_MODEL_LOGGING from mlflow.exceptions imp...
129
5,030
mlflow
tests/utils/test_string_utils.py
.py
import pytest from mlflow.utils.string_utils import ( format_table_cell_value, is_string_type, mslex_quote, strip_prefix, strip_suffix, ) @pytest.mark.parametrize( (("original", "prefix", "expected")), [("smoketest", "smoke", "test"), ("", "test", ""), ("", "", ""), ("test", "", "test")],...
95
2,956
mlflow
tests/utils/test_unity_catalog_utils.py
.py
import pytest from mlflow.entities.logged_model_parameter import LoggedModelParameter as ModelParam from mlflow.entities.metric import Metric from mlflow.entities.model_registry import ( ModelVersion, ModelVersionDeploymentJobState, ModelVersionTag, RegisteredModel, RegisteredModelAlias, Regist...
556
18,255
mlflow
tests/utils/test_databricks_tracing_utils.py
.py
import json import pytest from google.protobuf.timestamp_pb2 import Timestamp import mlflow from mlflow.entities import ( AssessmentSource, Expectation, Feedback, Trace, TraceData, TraceInfo, TraceState, ) from mlflow.entities.trace_location import ( InferenceTableLocation, MlflowE...
519
20,601
mlflow
tests/utils/test_env_pack.py
.py
import subprocess import sys import tarfile import venv from pathlib import Path from unittest import mock import pytest import yaml from mlflow.exceptions import MlflowException from mlflow.utils import env_pack from mlflow.utils.databricks_utils import DatabricksRuntimeVersion from mlflow.utils.env_pack import EnvP...
424
15,584
mlflow
tests/utils/test_async_logging_queue.py
.py
import contextlib import io import pickle import random import threading import time import uuid from unittest.mock import MagicMock, patch import pytest import mlflow.utils.async_logging.async_logging_queue from mlflow import MlflowException from mlflow.entities.metric import Metric from mlflow.entities.param import...
440
15,131
mlflow
tests/utils/test_git_utils.py
.py
import pytest from mlflow.utils.git_utils import _strip_credentials_from_url @pytest.mark.parametrize( ("url", "expected"), [ # HTTPS with username + password (token) ("https://user:token@github.com/foo/bar.git", "https://github.com/foo/bar.git"), # HTTPS with token-only userinfo (Git...
38
1,577
mlflow
tests/utils/test_crypto.py
.py
import json import os import pytest from mlflow.exceptions import MlflowException from mlflow.utils.crypto import ( AES_256_KEY_LENGTH, GCM_NONCE_LENGTH, KEKManager, _create_aad, _decrypt_secret, _encrypt_secret, _encrypt_with_aes_gcm, _generate_dek, _mask_secret_value, _mask_s...
624
18,858
mlflow
tests/utils/test_yaml_utils.py
.py
import codecs import os from mlflow.utils.yaml_utils import ( read_yaml, safe_edit_yaml, write_yaml, ) from tests.helper_functions import random_file, random_int def test_yaml_read_and_write(tmp_path): temp_dir = str(tmp_path) yaml_file = random_file("yaml") long_value = 1 data = { ...
77
2,134
mlflow
tests/utils/test_uv_utils.py
.py
import subprocess from unittest import mock import pytest from packaging.version import Version from mlflow.environment_variables import MLFLOW_UV_AUTO_DETECT from mlflow.utils.environment import infer_pip_requirements from mlflow.utils.uv_utils import ( _PYPROJECT_FILE, _UV_LOCK_FILE, copy_uv_project_fil...
868
28,171
mlflow
tests/utils/test_uri.py
.py
import os import pathlib import posixpath import pytest from mlflow.exceptions import MlflowException from mlflow.store.db.db_types import DATABASE_ENGINES from mlflow.utils.os import is_windows from mlflow.utils.uri import ( add_databricks_profile_info_to_artifact_uri, append_to_uri_path, append_to_uri_q...
1,034
39,732
mlflow
tests/utils/test_workspace_utils.py
.py
from __future__ import annotations import os from mlflow.environment_variables import MLFLOW_WORKSPACE from mlflow.utils.workspace_context import ( ServerWorkspaceContext, WorkspaceContext, clear_server_request_workspace, get_request_workspace, ) from mlflow.utils.workspace_utils import ( DEFAULT_...
56
1,756
mlflow
tests/utils/test_async_artifacts_logging_queue.py
.py
import io import pickle import random import threading import time import pytest from PIL import Image from mlflow import MlflowException from mlflow.utils.async_logging.async_artifacts_logging_queue import AsyncArtifactsLoggingQueue TOTAL_ARTIFACTS = 5 class RunArtifacts: def __init__(self, throw_exception_on...
281
9,308
mlflow
tests/utils/test_mime_type_utils.py
.py
import pytest from mlflow.utils.mime_type_utils import _guess_mime_type from mlflow.utils.os import is_windows @pytest.mark.skipif(is_windows(), reason="This test fails on Windows") @pytest.mark.parametrize( ("file_path", "expected_mime_type"), [ ("c.txt", "text/plain"), ("c.pkl", "applicatio...
40
1,335
mlflow
tests/utils/test_provider_filter.py
.py
import pytest from mlflow.utils.provider_filter import ( _parse_provider_list, filter_providers, is_provider_allowed, ) @pytest.mark.parametrize( ("input_value", "expected"), [ (None, frozenset()), ("", frozenset()), ("openai", frozenset({"openai"})), ("openai,anth...
78
2,947
mlflow
tests/utils/test_jsonpath_utils.py
.py
import pytest from mlflow.utils.jsonpath_utils import ( filter_json_by_fields, jsonpath_extract_values, split_path_respecting_backticks, validate_field_paths, ) def test_jsonpath_extract_values_simple(): data = {"info": {"trace_id": "tr-123", "state": "OK"}} values = jsonpath_extract_values(d...
251
9,111
mlflow
tests/utils/test_gorilla.py
.py
import pytest from mlflow.utils import gorilla class Delegator: def __init__(self, delegated_fn): self.delegated_fn = delegated_fn def __get__(self, instance, owner): return self.delegated_fn def delegate(delegated_fn): return lambda fn: Delegator(delegated_fn) def gen_class_A_B(): ...
190
5,386
mlflow
tests/utils/test_environment.py
.py
import importlib.metadata import os from unittest import mock import pytest import yaml from mlflow.exceptions import MlflowException from mlflow.utils.environment import ( _contains_mlflow_requirement, _deduplicate_requirements, _get_pip_deps, _get_pip_requirement_specifier, _is_mlflow_requiremen...
497
20,777
mlflow
tests/utils/test_proto_json_utils.py
.py
import base64 import datetime import json import numpy as np import pandas as pd import pytest from google.protobuf.text_format import Parse as ParseTextIntoProto from mlflow.entities import Experiment, Metric from mlflow.entities.model_registry import ModelVersion, RegisteredModel from mlflow.exceptions import Mlflo...
712
25,695
mlflow
tests/utils/test_process_utils.py
.py
import os import uuid import pytest from mlflow.utils.os import is_windows from mlflow.utils.process import cache_return_value_per_process @cache_return_value_per_process def _gen_random_str1(v): return str(v) + uuid.uuid4().hex @cache_return_value_per_process def _gen_random_str2(v): return str(v) + uuid...
67
1,931
mlflow
tests/utils/test_doctor.py
.py
from unittest import mock import mlflow def test_doctor(capsys): mlflow.doctor() captured = capsys.readouterr() assert f"MLflow version: {mlflow.__version__}" in captured.out def test_doctor_active_run(capsys): with mlflow.start_run() as run: mlflow.doctor() captured = capsys.readou...
28
780