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/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
mlflow
tests/utils/test_validation.py
.py
import copy import socket import time from unittest.mock import patch import pytest from mlflow.entities import Metric, Param, RunTag from mlflow.environment_variables import MLFLOW_ARTIFACT_LOCATION_MAX_LENGTH from mlflow.exceptions import MlflowException from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VA...
784
26,931
mlflow
tests/utils/test_arguments_utils.py
.py
import functools import pytest from mlflow.utils.arguments_utils import _get_arg_names def no_args(): pass def positional(a, b): return a, b def keyword(a=0, b=0): return a, b def positional_and_keyword(a, b=0): return a, b def keyword_only(*, a, b=0): return a, b def var_positional(*a...
61
1,062
mlflow
tests/utils/test_databricks_sql_warehouse.py
.py
import time from datetime import timedelta from unittest import mock import pytest from databricks.sdk.service.sql import State from mlflow.environment_variables import ( MLFLOW_SQL_WAREHOUSE_AUTO_START, MLFLOW_SQL_WAREHOUSE_AUTO_START_TIMEOUT_SECONDS, ) from mlflow.exceptions import MlflowException from mlfl...
130
4,784
mlflow
tests/utils/test_name_utils.py
.py
from mlflow.utils.name_utils import _generate_random_name, _generate_unique_integer_id def test_random_name_generation(): # Validate exhausted loop truncation name = _generate_random_name(max_length=8) assert len(name) == 8 # Validate default behavior while calling 1000 times that names end in intege...
21
775
mlflow
tests/utils/test_request_utils.py
.py
import socket import subprocess import sys from unittest import mock import pytest from requests.adapters import HTTPAdapter from mlflow.utils import request_utils from mlflow.utils.request_utils import ( TCPKeepAliveHTTPAdapter, _build_socket_options, ) def test_request_utils_does_not_import_mlflow(tmp_pat...
254
8,825
mlflow
tests/utils/test_docstring_utils.py
.py
import warnings from mlflow.utils.docstring_utils import ( ParamDocs, _indent, docstring_version_compatibility_warning, format_docstring, ) def test_indent_empty(): a = "" b = " " * 4 assert _indent(a, b) == a def test_indent_single_line(): a = "x" b = " " * 4 assert _indent...
174
3,661
mlflow
tests/utils/test_logging_utils.py
.py
import logging import os import re import subprocess import sys import uuid from io import StringIO import pytest import mlflow from mlflow.utils import logging_utils from mlflow.utils.logging_utils import ( LOGGING_LINE_FORMAT, SensitiveQueryParamFilter, _configure_mlflow_loggers, _redact_sensitive_q...
383
11,819
mlflow
tests/utils/test_autologging_utils.py
.py
import warnings from threading import Thread from mlflow import MlflowClient from mlflow.entities import Metric from mlflow.utils.autologging_utils.logging_and_warnings import ( _WarningsController, ) from mlflow.utils.autologging_utils.metrics_queue import ( _metrics_queue, _metrics_queue_lock, flush_...
96
3,592
mlflow
tests/utils/test_unity_catalog_oss_utils.py
.py
from mlflow.entities.model_registry import RegisteredModel from mlflow.protos.unity_catalog_messages_pb2 import ( RegisteredModelInfo, ) from mlflow.utils._unity_catalog_oss_utils import get_registered_model_from_uc_oss_proto def test_registered_model_from_uc_oss_proto(): expected_registered_model = Registere...
27
822
mlflow
tests/utils/test_data.py
.py
import os from mlflow.projects import _project_spec from mlflow.utils.data_utils import is_uri TEST_DIR = "tests" TEST_PROJECT_DIR = os.path.join(TEST_DIR, "resources", "example_project") def load_project(): return _project_spec.load_project(directory=TEST_PROJECT_DIR) def test_is_uri(): assert is_uri("s3...
20
509
mlflow
tests/utils/test_credentials.py
.py
from unittest import mock from unittest.mock import patch import pytest from mlflow import get_tracking_uri from mlflow.environment_variables import MLFLOW_TRACKING_PASSWORD, MLFLOW_TRACKING_USERNAME from mlflow.exceptions import MlflowException from mlflow.utils.credentials import login, read_mlflow_creds def test...
151
4,918
mlflow
tests/utils/test_databricks_utils.py
.py
import builtins import json import os import platform import sys import time from unittest import mock import pytest import mlflow from mlflow.exceptions import MlflowException from mlflow.legacy_databricks_cli.configure.provider import ( DatabricksConfig, DatabricksModelServingConfigProvider, ) from mlflow.u...
1,467
58,783
mlflow
tests/utils/test_annotations.py
.py
import re from dataclasses import dataclass, fields import pytest from mlflow.utils.annotations import _get_min_indent_of_docstring, deprecated, keyword_only # Suppress expected deprecation warnings from test fixtures pytestmark = pytest.mark.filterwarnings("ignore:.*is deprecated.*:FutureWarning") class MyClass: ...
329
8,393
mlflow
tests/utils/test_rest_utils.py
.py
import re import time import warnings from unittest import mock import numpy import pytest import requests from mlflow.deployments.databricks import DatabricksDeploymentClient from mlflow.environment_variables import ( _MLFLOW_DATABRICKS_TRAFFIC_ID, MLFLOW_HTTP_REQUEST_TIMEOUT, ) from mlflow.exceptions import...
1,043
40,718
mlflow
tests/utils/test_python_env.py
.py
from unittest import mock import pytest from mlflow.utils import PYTHON_VERSION from mlflow.utils.environment import _PythonEnv def test_constructor_argument_validation(): with pytest.raises(TypeError, match="`python` must be a string"): _PythonEnv(python=1) with pytest.raises(TypeError, match="`bu...
147
3,577
mlflow
tests/utils/test_utils.py
.py
import importlib.metadata import socket from unittest import mock import pytest from packaging.version import Version from mlflow.utils import ( AttrDict, _chunk_dict, _get_fully_qualified_class_name, _truncate_dict, get_installed_version, merge_dicts, ) def test_truncate_dict(): d = {"1...
255
7,273
mlflow
tests/utils/test_time.py
.py
import time from mlflow.utils.time import Timer def test_timer(): with Timer() as t: time.sleep(0.1) assert f"{t}" == f"{t.elapsed}" assert f"{t:.3f}" == f"{t.elapsed:.3f}"
12
197
mlflow
tests/utils/test_requirements_utils.py
.py
import importlib import os import sys from importlib.metadata import version from unittest import mock import cloudpickle import importlib_metadata import pytest import mlflow import mlflow.utils.requirements_utils from mlflow.exceptions import MlflowException from mlflow.utils.environment import infer_pip_requiremen...
779
28,482
mlflow
tests/utils/test_resources/dummy_package/pandas.py
.py
# This module is meant to test shadowing of the 3rd party module raise Exception( "This package should not have been imported! " "This means that the sys.path was not configured correctly" )
6
199
mlflow
tests/utils/test_resources/dummy_package/operator.py
.py
# This module is meant to test shadowing of the built-in operator module raise Exception( "This package should not have been imported! " "This means that the sys.path was not configured correctly" )
6
207
mlflow
tests/pyspark/optuna/test_study.py
.py
import logging import os import numpy as np import pyspark import pytest from optuna.exceptions import TrialPruned from optuna.pruners import NopPruner, ThresholdPruner from optuna.samplers import TPESampler from optuna.study import StudyDirection from optuna.trial import TrialState from packaging.version import Versi...
386
13,398
mlflow
tests/gateway/test_openai_compatibility.py
.py
from unittest import mock import openai import pytest from mlflow.gateway.providers.openai import OpenAIProvider from tests.gateway.tools import ( UvicornGateway, save_yaml, ) @pytest.fixture(scope="module") def config(): return { "endpoints": [ { "name": "chat", ...
160
4,707
mlflow
tests/gateway/test_gateway_app.py
.py
from unittest import mock import pytest from fastapi.testclient import TestClient from mlflow.exceptions import MlflowException from mlflow.gateway.app import create_app_from_config, create_app_from_env from mlflow.gateway.config import GatewayConfig from mlflow.gateway.constants import ( MLFLOW_GATEWAY_CRUD_ENDP...
279
8,585
mlflow
tests/gateway/test_budget_tracker.py
.py
from datetime import datetime, timedelta, timezone from unittest.mock import patch import pytest from mlflow.entities.gateway_budget_policy import ( BudgetAction, BudgetDuration, BudgetDurationUnit, BudgetTargetScope, BudgetUnit, GatewayBudgetPolicy, ) from mlflow.gateway.budget_tracker import...
654
23,334
mlflow
tests/gateway/test_gateway_config_parsing.py
.py
import re import pytest import yaml from mlflow.exceptions import MlflowException from mlflow.gateway.config import ( AnthropicConfig, EndpointConfig, LiteLLMConfig, OpenAIConfig, _load_gateway_config, _resolve_api_key_from_input, _save_route_config, ) from mlflow.gateway.utils import asse...
454
15,759
mlflow
tests/gateway/test_runner.py
.py
from pathlib import Path import pytest from tests.gateway.tools import Gateway, save_yaml BASE_ROUTE = "/api/2.0/endpoints/" @pytest.fixture def basic_config_dict(): return { "endpoints": [ { "name": "completions-gpt4", "endpoint_type": "llm/v1/completions", ...
231
7,059
mlflow
tests/gateway/test_tracing_utils.py
.py
import asyncio import json from typing import Any import pytest import mlflow from mlflow.entities import SpanType from mlflow.gateway.constants import MLFLOW_GATEWAY_CALLER_HEADER from mlflow.gateway.schemas.chat import StreamResponsePayload from mlflow.gateway.tracing_utils import ( _extract_caller, _get_mo...
1,135
41,606
mlflow
tests/gateway/test_provider_registry.py
.py
import pytest from mlflow.exceptions import MlflowException from mlflow.gateway.provider_registry import provider_registry def test_registry_keys_returns_all_providers_by_default(): keys = provider_registry.keys() assert len(keys) > 0 assert "openai" in keys assert "anthropic" in keys def test_regi...
37
1,188