code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def test_edge_cases_zero_max_count_text_list():
"""Test handling of zero max_count for text list."""
input_text_list = InputTextList(max_count=0)
assert input_text_list.max_count == 0 | Test handling of zero max_count for text list. | test_edge_cases_zero_max_count_text_list | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_edge_cases_special_and_unicode_characters_in_options(options):
"""Test handling of special characters and unicode in categorical options."""
input_cat = InputCategorical(options=options)
assert input_cat.options == options | Test handling of special characters and unicode in categorical options. | test_edge_cases_special_and_unicode_characters_in_options | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_create_label_schema_calls_to_databricks_input():
"""Test that create_label_schema calls _to_databricks_input on the input."""
input_cat = InputCategorical(options=["good", "bad"])
# Mock the databricks modules and review app
with patch("databricks.agents.review_app.get_review_app") as mock_get... | Test that create_label_schema calls _to_databricks_input on the input. | test_create_label_schema_calls_to_databricks_input | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_api_integration_with_all_input_types(input_type, schema_name):
"""Test that API integration works with all input types."""
# Mock the databricks modules and review app
with patch("databricks.agents.review_app.get_review_app") as mock_get_app:
mock_app = MagicMock()
mock_app.create_l... | Test that API integration works with all input types. | test_api_integration_with_all_input_types | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_databricks_label_schemas_is_importable():
"""Test that all constants, classes, and functions are importable."""
# Test constants
assert label_schemas.EXPECTED_FACTS == EXPECTED_FACTS
assert label_schemas.GUIDELINES == GUIDELINES
assert label_schemas.EXPECTED_RESPONSE == EXPECTED_RESPONSE
... | Test that all constants, classes, and functions are importable. | test_databricks_label_schemas_is_importable | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_simple_function_recreation():
"""Test basic function recreation with simple logic."""
source = "return x + y"
signature = "(x, y)"
func_name = "add_func"
recreated = recreate_function(source, signature, func_name)
assert recreated is not None
assert recreated.__name__ == func_name... | Test basic function recreation with simple logic. | test_simple_function_recreation | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_function_with_control_flow():
"""Test recreation of function with if/else logic."""
source = """if x > 0:
return "positive"
else:
return "non-positive" """
signature = "(x)"
func_name = "classify_number"
recreated = recreate_function(source, signature, func_name)
assert recrea... | Test recreation of function with if/else logic. | test_function_with_control_flow | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_function_with_loop():
"""Test recreation of function with loop logic."""
source = """total = 0
for i in range(n):
total += i
return total"""
signature = "(n)"
func_name = "sum_range"
recreated = recreate_function(source, signature, func_name)
assert recreated is not None
asser... | Test recreation of function with loop logic. | test_function_with_loop | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_function_with_multiple_parameters():
"""Test function with multiple parameters and default values."""
source = """if threshold is None:
threshold = 5
return len(text) > threshold"""
signature = "(text, threshold=None)"
func_name = "length_check"
recreated = recreate_function(source, si... | Test function with multiple parameters and default values. | test_function_with_multiple_parameters | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_function_creating_feedback_object():
"""Test recreation of function that creates MLflow Feedback objects."""
source = """import re
words = re.findall(r'\\b\\w+\\b', text)
return Feedback(value=len(words), rationale=f"Found {len(words)} words")"""
signature = "(text)"
func_name = "word_counter"
... | Test recreation of function that creates MLflow Feedback objects. | test_function_creating_feedback_object | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_function_creating_assessment_object():
"""Test recreation of function that creates MLflow Assessment objects."""
# Note: Assessment constructor doesn't take 'value' directly - it's an abstract base
# Use Feedback instead, which is a concrete subclass of Assessment
source = """score = 1 if "good... | Test recreation of function that creates MLflow Assessment objects. | test_function_creating_assessment_object | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_complex_logic_function():
"""Test recreation of function with complex nested logic."""
source = """result = {}
for item in items:
if isinstance(item, str):
result[item] = len(item)
elif isinstance(item, (int, float)):
result[str(item)] = item * 2
return result"""
signature =... | Test recreation of function with complex nested logic. | test_complex_logic_function | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_signature_with_whitespace():
"""Test signature parsing with extra whitespace."""
source = "return a + b"
signature = "( a , b )"
func_name = "add_with_spaces"
recreated = recreate_function(source, signature, func_name)
assert recreated is not None
assert recreated(3, 7) == 10 | Test signature parsing with extra whitespace. | test_signature_with_whitespace | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_signature_with_defaults():
"""Test signature with default parameter values."""
source = "return base ** exponent"
signature = "(base, exponent=2)"
func_name = "power"
recreated = recreate_function(source, signature, func_name)
assert recreated is not None
assert recreated(3) == 9 ... | Test signature with default parameter values. | test_signature_with_defaults | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_complex_signature():
"""Test complex signature with multiple parameters and defaults."""
source = """if data is None:
data = []
return f"{prefix}: {len(data)} items" + (suffix or "")"""
signature = "(data=None, prefix='Result', suffix=None)"
func_name = "format_result"
recreated = recr... | Test complex signature with multiple parameters and defaults. | test_complex_signature | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_empty_signature_string():
"""Test that empty signature string returns None."""
source = "return 1"
signature = ""
func_name = "empty_sig"
recreated = recreate_function(source, signature, func_name)
assert recreated is None | Test that empty signature string returns None. | test_empty_signature_string | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_function_with_unavailable_import():
"""Test that function using unavailable imports fails gracefully."""
# Import errors occur at execution time, not definition time
source = """from some_nonexistent_module import NonExistentClass
return NonExistentClass()"""
signature = "()"
func_name = "u... | Test that function using unavailable imports fails gracefully. | test_function_with_unavailable_import | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_function_with_undefined_variable():
"""Test that function using undefined variables fails gracefully."""
source = "return undefined_variable * 2"
signature = "()"
func_name = "use_undefined"
recreated = recreate_function(source, signature, func_name)
# Function is created but will fai... | Test that function using undefined variables fails gracefully. | test_function_with_undefined_variable | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_function_with_syntax_error():
"""Test that function with syntax errors fails gracefully."""
source = "if x > 0\n return True" # Missing colon
signature = "(x)"
func_name = "syntax_error_func"
recreated = recreate_function(source, signature, func_name)
# Should return None due to s... | Test that function with syntax errors fails gracefully. | test_function_with_syntax_error | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_function_using_builtin_modules():
"""Test that function can use standard library modules."""
source = """import json
import re
data = {"count": len(re.findall(r'\\w+', text))}
return json.dumps(data)"""
signature = "(text)"
func_name = "json_word_count"
recreated = recreate_function(source... | Test that function can use standard library modules. | test_function_using_builtin_modules | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_logging_on_failure(mock_logger):
"""Test that failures are logged appropriately."""
source = "invalid python syntax !!!"
signature = "()"
func_name = "bad_function"
recreated = recreate_function(source, signature, func_name)
assert recreated is None
mock_logger.assert_called_once_... | Test that failures are logged appropriately. | test_logging_on_failure | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_mlflow_imports_available():
"""Test that MLflow imports are available in the namespace."""
source = """# Test all available MLflow imports
feedback = Feedback(value=True, rationale="test")
# AssessmentSource should be available too
from mlflow.entities.assessment_source import AssessmentSourceType
sour... | Test that MLflow imports are available in the namespace. | test_mlflow_imports_available | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_function_name_in_namespace():
"""Test that function name is correctly set in the local namespace."""
source = "return 'success'"
signature = "()"
func_name = "test_name_func"
recreated = recreate_function(source, signature, func_name)
assert recreated is not None
assert recreated.... | Test that function name is correctly set in the local namespace. | test_function_name_in_namespace | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_indentation_handling():
"""Test that source code indentation is handled correctly."""
# Source without indentation - should be indented by the function
source = """x = 1
y = 2
return x + y"""
signature = "()"
func_name = "indentation_test"
recreated = recreate_function(source, signatur... | Test that source code indentation is handled correctly. | test_indentation_handling | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_empty_source_code():
"""Test handling of empty source code."""
source = ""
signature = "()"
func_name = "empty_func"
# Empty source code should cause syntax error during function definition
recreated = recreate_function(source, signature, func_name)
# Should return None due to inv... | Test handling of empty source code. | test_empty_source_code | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_function_with_import_error_at_runtime():
"""Test that functions with import errors at runtime can be recreated but fail when called."""
# Import that doesn't exist is referenced but not imported in the function
source = """try:
return NonExistentClass()
except NameError:
return "import_fail... | Test that functions with import errors at runtime can be recreated but fail when called. | test_function_with_import_error_at_runtime | python | mlflow/mlflow | tests/genai/scorers/test_scorer_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_scorer_utils.py | Apache-2.0 |
def test_decorator_scorer_serialization_format():
"""Test that decorator scorers serialize with correct format."""
@scorer(name="test_scorer", aggregations=["mean"])
def test_scorer(outputs):
return outputs == "correct"
serialized = test_scorer.model_dump()
# Check required fields for dec... | Test that decorator scorers serialize with correct format. | test_decorator_scorer_serialization_format | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_builtin_scorer_serialization_format():
"""Test that builtin scorers serialize with correct format."""
from mlflow.genai.scorers.builtin_scorers import RelevanceToQuery
serialized = RelevanceToQuery().model_dump()
# Check required top-level fields for builtin scorers
assert serialized["nam... | Test that builtin scorers serialize with correct format. | test_builtin_scorer_serialization_format | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_simple_scorer_round_trip():
"""Test basic round-trip serialization and execution."""
@scorer
def simple_scorer(outputs):
return outputs == "correct"
# Test original functionality
assert simple_scorer(outputs="correct") is True
assert simple_scorer(outputs="wrong") is False
... | Test basic round-trip serialization and execution. | test_simple_scorer_round_trip | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_custom_name_and_aggregations_round_trip():
"""Test round-trip with custom name and aggregations."""
@scorer(name="length_check", aggregations=["mean", "max"])
def my_scorer(inputs, outputs):
return len(outputs) > len(inputs)
# Test original
assert my_scorer(inputs="hi", outputs="h... | Test round-trip with custom name and aggregations. | test_custom_name_and_aggregations_round_trip | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_multiple_parameters_round_trip():
"""Test round-trip with multiple parameters."""
@scorer
def multi_param_scorer(inputs, outputs, expectations):
return outputs.startswith(inputs) and len(outputs) > expectations.get("min_length", 0)
# Test original
test_args = {"inputs": "Hello", "... | Test round-trip with multiple parameters. | test_multiple_parameters_round_trip | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_complex_logic_round_trip():
"""Test round-trip with complex control flow and logic."""
@scorer
def complex_scorer(outputs):
if not outputs:
return 0
words = outputs.split()
score = 0
for word in words:
if word.isupper():
scor... | Test round-trip with complex control flow and logic. | test_complex_logic_round_trip | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_imports_and_feedback_round_trip():
"""Test round-trip with imports and Feedback return."""
@scorer
def feedback_scorer(outputs):
import re # clint: disable=lazy-builtin-import
pattern = r"\b\w+\b"
words = re.findall(pattern, outputs)
return Feedback(value=len(word... | Test round-trip with imports and Feedback return. | test_imports_and_feedback_round_trip | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_default_parameters_round_trip():
"""Test round-trip with default parameter values."""
@scorer
def default_scorer(outputs, threshold=5):
return len(outputs) > threshold
# Test original with and without default
assert default_scorer(outputs="short") is False # len=5, not > 5
as... | Test round-trip with default parameter values. | test_default_parameters_round_trip | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_end_to_end_complex_round_trip():
"""Test complex end-to-end scenario with all features."""
@scorer(name="complete_test", aggregations=["mean", "max"])
def complete_scorer(inputs, outputs, expectations):
input_words = len(inputs.split())
output_words = len(outputs.split())
e... | Test complex end-to-end scenario with all features. | test_end_to_end_complex_round_trip | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_builtin_scorer_round_trip():
"""Test builtin scorer serialization and execution with mocking."""
# from mlflow.genai.scorers import relevance_to_query
from mlflow.genai.scorers.builtin_scorers import RelevanceToQuery
# Round-trip serialization
serialized = RelevanceToQuery().model_dump()
... | Test builtin scorer serialization and execution with mocking. | test_builtin_scorer_round_trip | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_builtin_scorer_with_parameters_round_trip():
"""Test builtin scorer with custom parameters (like Guidelines with guidelines)."""
from mlflow.genai.scorers.builtin_scorers import Guidelines
# Create scorer with custom parameters
tone = (
"The response must maintain a courteous, respectf... | Test builtin scorer with custom parameters (like Guidelines with guidelines). | test_builtin_scorer_with_parameters_round_trip | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_direct_subclass_scorer_rejected():
"""Test that direct subclassing of Scorer is rejected during serialization."""
class DirectSubclassScorer(Scorer):
"""An unsupported direct subclass of Scorer."""
def __init__(self, **data):
super().__init__(name="direct_subclass", **data... | Test that direct subclassing of Scorer is rejected during serialization. | test_direct_subclass_scorer_rejected | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_builtin_scorer_with_aggregations_round_trip():
"""Test builtin scorer with aggregations serialization and execution."""
from mlflow.genai.scorers.builtin_scorers import RelevanceToQuery
scorer_with_aggs = RelevanceToQuery(name="relevance_with_aggs", aggregations=["mean", "max"])
# Test that a... | Test builtin scorer with aggregations serialization and execution. | test_builtin_scorer_with_aggregations_round_trip | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_builtin_scorer_with_custom_name_compatibility():
"""Test builtin scorer with custom name from fixed serialized string."""
# Fixed serialized string for Guidelines scorer with custom name and parameters
fixed_serialized_data = {
"name": "custom_guidelines",
"aggregations": ["mean", "... | Test builtin scorer with custom name from fixed serialized string. | test_builtin_scorer_with_custom_name_compatibility | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_custom_scorer_compatibility_from_fixed_string():
"""Test that custom scorers can be deserialized from a fixed serialized string."""
# Fixed serialized string representing a simple custom scorer
fixed_serialized_data = {
"name": "word_count_scorer",
"aggregations": ["mean"],
... | Test that custom scorers can be deserialized from a fixed serialized string. | test_custom_scorer_compatibility_from_fixed_string | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_complex_custom_scorer_compatibility():
"""Test complex custom scorer with multiple parameters from fixed string."""
# Fixed serialized string for a more complex custom scorer
fixed_serialized_data = {
"name": "length_comparison",
"aggregations": None,
"mlflow_version": "2.9.... | Test complex custom scorer with multiple parameters from fixed string. | test_complex_custom_scorer_compatibility | python | mlflow/mlflow | tests/genai/scorers/test_serialization.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_serialization.py | Apache-2.0 |
def test_validate_data_with_expectations(mock_logger, sample_rag_trace):
"""Test that expectations are unwrapped and validated properly"""
data = pd.DataFrame(
{
"inputs": [{"question": "input1"}, {"question": "input2"}],
"outputs": ["output1", "output2"],
"trace": [s... | Test that expectations are unwrapped and validated properly | test_validate_data_with_expectations | python | mlflow/mlflow | tests/genai/scorers/test_validation.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_validation.py | Apache-2.0 |
def test_validate_data_with_correctness(expectations, mock_logger):
"""Correctness scorer requires one of expected_facts or expected_response"""
data = pd.DataFrame(
{
"inputs": [{"question": "input1"}, {"question": "input2"}],
"outputs": ["output1", "output2"],
"expe... | Correctness scorer requires one of expected_facts or expected_response | test_validate_data_with_correctness | python | mlflow/mlflow | tests/genai/scorers/test_validation.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/scorers/test_validation.py | Apache-2.0 |
def test_check_model_prediction_variable_args():
"""
If the function has variable positional arguments (*args), it is not supported.
"""
def fn(*args):
return "response"
with pytest.raises(MlflowException, match=r"The `predict_fn` has dynamic") as e:
check_model_prediction(fn, {"qu... |
If the function has variable positional arguments (*args), it is not supported.
| test_check_model_prediction_variable_args | python | mlflow/mlflow | tests/genai/utils/test_data_validation.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/utils/test_data_validation.py | Apache-2.0 |
def test_model_load_succeeds_with_missing_data_key_when_data_exists_at_default_path(
h2o_iris_model, model_path
):
"""
This is a backwards compatibility test to ensure that models saved in MLflow version <= 0.7.0
can be loaded successfully. These models are missing the `data` flavor configuration key.
... |
This is a backwards compatibility test to ensure that models saved in MLflow version <= 0.7.0
can be loaded successfully. These models are missing the `data` flavor configuration key.
| test_model_load_succeeds_with_missing_data_key_when_data_exists_at_default_path | python | mlflow/mlflow | tests/h2o/test_h2o_model_export.py | https://github.com/mlflow/mlflow/blob/master/tests/h2o/test_h2o_model_export.py | Apache-2.0 |
def invoke_cli_runner(*args, **kwargs):
"""
Helper method to invoke the CliRunner while asserting that the exit code is actually 0.
"""
res = CliRunner().invoke(*args, **kwargs)
assert res.exit_code == 0, f"Got non-zero exit code {res.exit_code}. Output is: {res.output}"
return res |
Helper method to invoke the CliRunner while asserting that the exit code is actually 0.
| invoke_cli_runner | python | mlflow/mlflow | tests/integration/utils.py | https://github.com/mlflow/mlflow/blob/master/tests/integration/utils.py | Apache-2.0 |
def _call(self, prompt: str, stop: Optional[list[str]] = None, run_manager=None) -> str:
"""First try to lookup in queries, else return 'foo' or 'bar'."""
if self.queries is not None:
return self.queries[prompt]
if stop is None:
return "foo"
else:
retu... | First try to lookup in queries, else return 'foo' or 'bar'. | _call | python | mlflow/mlflow | tests/langchain/test_langchain_model_export.py | https://github.com/mlflow/mlflow/blob/master/tests/langchain/test_langchain_model_export.py | Apache-2.0 |
def get_weather(city: Literal["nyc", "sf"]):
"""Use this to get weather information."""
if city == "nyc":
return "It might be cloudy in nyc"
elif city == "sf":
return "It's always sunny in sf" | Use this to get weather information. | get_weather | python | mlflow/mlflow | tests/langgraph/sample_code/langgraph_prebuilt.py | https://github.com/mlflow/mlflow/blob/master/tests/langgraph/sample_code/langgraph_prebuilt.py | Apache-2.0 |
def test_load_pyfunc_succeeds_for_older_models_with_pyfunc_data_field(lgb_model, model_path):
"""
This test verifies that LightGBM models saved in older versions of MLflow are loaded
successfully by ``mlflow.pyfunc.load_model``. These older models specify a pyfunc ``data``
field referring directly to a ... |
This test verifies that LightGBM models saved in older versions of MLflow are loaded
successfully by ``mlflow.pyfunc.load_model``. These older models specify a pyfunc ``data``
field referring directly to a LightGBM model file. Newer models also have the
``model_class`` in LightGBM flavor.
| test_load_pyfunc_succeeds_for_older_models_with_pyfunc_data_field | python | mlflow/mlflow | tests/lightgbm/test_lightgbm_model_export.py | https://github.com/mlflow/mlflow/blob/master/tests/lightgbm/test_lightgbm_model_export.py | Apache-2.0 |
def settings(monkeypatch, mock_openai):
"""Set the LLM and Embedding model to the mock OpenAI server."""
monkeypatch.setenvs(
{
"OPENAI_API_KEY": "test",
"OPENAI_API_BASE": mock_openai,
}
)
monkeypatch.setattr(Settings, "llm", OpenAI())
monkeypatch.setattr(Set... | Set the LLM and Embedding model to the mock OpenAI server. | settings | python | mlflow/mlflow | tests/llama_index/conftest.py | https://github.com/mlflow/mlflow/blob/master/tests/llama_index/conftest.py | Apache-2.0 |
def assert_base_model_reqs():
"""
Helper function for testing model requirements. Asserts that the
contents of requirements.txt and conda.yaml are as expected, then
returns their filepaths so mutations can be performed.
"""
import cloudpickle
class MyModel(mlflow.pyfunc.PythonModel):
... |
Helper function for testing model requirements. Asserts that the
contents of requirements.txt and conda.yaml are as expected, then
returns their filepaths so mutations can be performed.
| assert_base_model_reqs | python | mlflow/mlflow | tests/models/test_cli.py | https://github.com/mlflow/mlflow/blob/master/tests/models/test_cli.py | Apache-2.0 |
def test_pyfunc_representation_of_float32_model_casts_and_evaluates_float64_inputs(
onnx_model_multiple_inputs_float32, model_path, data_multiple_inputs, predicted_multiple_inputs
):
"""
The ``python_function`` representation of an MLflow model with the ONNX flavor
casts 64-bit floats to 32-bit floats a... |
The ``python_function`` representation of an MLflow model with the ONNX flavor
casts 64-bit floats to 32-bit floats automatically before evaluating, as opposed
to throwing an unexpected type exception. This behavior is implemented due
to the issue described in https://github.com/mlflow/mlflow/issues/12... | test_pyfunc_representation_of_float32_model_casts_and_evaluates_float64_inputs | python | mlflow/mlflow | tests/onnx/test_onnx_model_export.py | https://github.com/mlflow/mlflow/blob/master/tests/onnx/test_onnx_model_export.py | Apache-2.0 |
def test_pyfunc_predict_supports_models_with_list_outputs(onnx_sklearn_model, model_path, data):
"""
https://github.com/mlflow/mlflow/issues/2499
User encountered issue where an sklearn model, converted to onnx, would return a list response.
The issue resulted in an error because MLflow assumed it would... | ERROR: type should be string, got "\n https://github.com/mlflow/mlflow/issues/2499\n User encountered issue where an sklearn model, converted to onnx, would return a list response.\n The issue resulted in an error because MLflow assumed it would be a numpy array. Therefore,\n the this test validates the service does not receive that error when using such a model.\n " | test_pyfunc_predict_supports_models_with_list_outputs | python | mlflow/mlflow | tests/onnx/test_onnx_model_export.py | https://github.com/mlflow/mlflow/blob/master/tests/onnx/test_onnx_model_export.py | Apache-2.0 |
def test_flush_batch_sends_data_to_mlflow(setup_storage):
"""Test that _flush_batch properly sends data to MLflow client."""
with patch("mlflow.optuna.storage.MlflowClient") as mock_client:
storage = setup_storage
run_id = "test-run-id"
mock_client_instance = MagicMock()
mock_cli... | Test that _flush_batch properly sends data to MLflow client. | test_flush_batch_sends_data_to_mlflow | python | mlflow/mlflow | tests/optuna/test_storage.py | https://github.com/mlflow/mlflow/blob/master/tests/optuna/test_storage.py | Apache-2.0 |
def test_flush_batch_does_nothing_for_empty_batch(setup_storage):
"""Test that _flush_batch does nothing when batch is empty."""
with patch("mlflow.optuna.storage.MlflowClient") as mock_client:
storage = setup_storage
run_id = "test-run-id"
# Create a mock instance that will be returned ... | Test that _flush_batch does nothing when batch is empty. | test_flush_batch_does_nothing_for_empty_batch | python | mlflow/mlflow | tests/optuna/test_storage.py | https://github.com/mlflow/mlflow/blob/master/tests/optuna/test_storage.py | Apache-2.0 |
def test_flush_batch_handles_nonexistent_run(setup_storage):
"""Test that _flush_batch handles nonexistent run gracefully."""
with patch("mlflow.optuna.storage.MlflowClient") as mock_client:
storage = setup_storage
run_id = "nonexistent-run"
# Create a mock instance that will be returned... | Test that _flush_batch handles nonexistent run gracefully. | test_flush_batch_handles_nonexistent_run | python | mlflow/mlflow | tests/optuna/test_storage.py | https://github.com/mlflow/mlflow/blob/master/tests/optuna/test_storage.py | Apache-2.0 |
def test_flush_all_batches_flushes_all_runs(setup_storage):
"""Test that flush_all_batches flushes all pending runs."""
storage = setup_storage
# Setup multiple runs with data
run_ids = ["run1", "run2", "run3"]
for run_id in run_ids:
storage._batch_queue[run_id] = {
"metrics": [... | Test that flush_all_batches flushes all pending runs. | test_flush_all_batches_flushes_all_runs | python | mlflow/mlflow | tests/optuna/test_storage.py | https://github.com/mlflow/mlflow/blob/master/tests/optuna/test_storage.py | Apache-2.0 |
def test_flush_all_batches_handles_empty_queue(setup_storage):
"""Test that flush_all_batches works with empty queue."""
storage = setup_storage
# Ensure batch queue is empty
storage._batch_queue = {}
# Create a spy on _flush_batch
with patch.object(storage, "_flush_batch") as mock_flush:
... | Test that flush_all_batches works with empty queue. | test_flush_all_batches_handles_empty_queue | python | mlflow/mlflow | tests/optuna/test_storage.py | https://github.com/mlflow/mlflow/blob/master/tests/optuna/test_storage.py | Apache-2.0 |
def runs_cancel_mock():
"""Mocks the Jobs Runs Cancel API request"""
with mock.patch(
"mlflow.projects.databricks.DatabricksJobRunner.jobs_runs_cancel"
) as runs_cancel_mock:
runs_cancel_mock.return_value = None
yield runs_cancel_mock | Mocks the Jobs Runs Cancel API request | runs_cancel_mock | python | mlflow/mlflow | tests/projects/test_databricks.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_databricks.py | Apache-2.0 |
def runs_get_mock():
"""Mocks the Jobs Runs Get API request"""
with mock.patch(
"mlflow.projects.databricks.DatabricksJobRunner.jobs_runs_get"
) as runs_get_mock:
yield runs_get_mock | Mocks the Jobs Runs Get API request | runs_get_mock | python | mlflow/mlflow | tests/projects/test_databricks.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_databricks.py | Apache-2.0 |
def test_run_databricks_validations(
tmp_path,
monkeypatch,
cluster_spec_mock,
dbfs_mocks,
set_tag_mock,
):
"""
Tests that running on Databricks fails before making any API requests if validations fail.
"""
monkeypatch.setenvs({"DATABRICKS_HOST": "test-host", "DATABRICKS_TOKEN": "foo... |
Tests that running on Databricks fails before making any API requests if validations fail.
| test_run_databricks_validations | python | mlflow/mlflow | tests/projects/test_databricks.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_databricks.py | Apache-2.0 |
def test_run_databricks(
runs_submit_mock,
runs_get_mock,
cluster_spec_mock,
set_tag_mock,
databricks_cluster_mlflow_run_cmd_mock,
monkeypatch,
):
"""Test running on Databricks with mocks."""
monkeypatch.setenv("DATABRICKS_HOST", "https://test-host")
monkeypatch.setenv("DATABRICKS_TO... | Test running on Databricks with mocks. | test_run_databricks | python | mlflow/mlflow | tests/projects/test_databricks.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_databricks.py | Apache-2.0 |
def test_databricks_http_request_integration(request):
"""Confirms that the databricks http request params can in fact be used as an HTTP request"""
def confirm_request_params(*args, **kwargs):
headers = DefaultRequestHeaderProvider().request_headers()
headers["Authorization"] = "Basic dXNlcjpw... | Confirms that the databricks http request params can in fact be used as an HTTP request | test_databricks_http_request_integration | python | mlflow/mlflow | tests/projects/test_databricks.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_databricks.py | Apache-2.0 |
def test_entry_point_compute_params():
"""
Tests that EntryPoint correctly computes a final set of parameters to use when running a project
"""
project = load_project()
entry_point = project.get_entry_point("greeter")
# Pass extra "excitement" param, use default value for `greeting` param
wi... |
Tests that EntryPoint correctly computes a final set of parameters to use when running a project
| test_entry_point_compute_params | python | mlflow/mlflow | tests/projects/test_entry_point.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_entry_point.py | Apache-2.0 |
def test_entry_point_compute_command():
"""
Tests that EntryPoint correctly computes the command to execute in order to run the entry point.
"""
project = load_project()
entry_point = project.get_entry_point("greeter")
with TempDir() as tmp:
storage_dir = tmp.path()
command = ent... |
Tests that EntryPoint correctly computes the command to execute in order to run the entry point.
| test_entry_point_compute_command | python | mlflow/mlflow | tests/projects/test_entry_point.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_entry_point.py | Apache-2.0 |
def test_path_parameter():
"""
Tests that MLflow file-download APIs get called when necessary for arguments of type `path`.
"""
project = load_project()
entry_point = project.get_entry_point("line_count")
with mock.patch(
"mlflow.tracking.artifact_utils._download_artifact_from_uri", retu... |
Tests that MLflow file-download APIs get called when necessary for arguments of type `path`.
| test_path_parameter | python | mlflow/mlflow | tests/projects/test_entry_point.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_entry_point.py | Apache-2.0 |
def test_uri_parameter():
"""Tests parameter resolution for parameters of type `uri`."""
project = load_project()
entry_point = project.get_entry_point("download_uri")
with (
mock.patch(
"mlflow.tracking.artifact_utils._download_artifact_from_uri"
) as download_uri_mock,
... | Tests parameter resolution for parameters of type `uri`. | test_uri_parameter | python | mlflow/mlflow | tests/projects/test_entry_point.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_entry_point.py | Apache-2.0 |
def test_invalid_run_mode():
"""Verify that we raise an exception given an invalid run mode"""
with pytest.raises(
ExecutionException, match="Got unsupported execution mode some unsupported mode"
):
mlflow.projects.run(uri=TEST_PROJECT_DIR, backend="some unsupported mode") | Verify that we raise an exception given an invalid run mode | test_invalid_run_mode | python | mlflow/mlflow | tests/projects/test_projects.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_projects.py | Apache-2.0 |
def test_run_with_parent():
"""Verify that if we are in a nested run, mlflow.projects.run() will have a parent_run_id."""
with mlflow.start_run():
parent_run_id = mlflow.active_run().info.run_id
submitted_run = mlflow.projects.run(
TEST_PROJECT_DIR,
entry_point="test_trac... | Verify that if we are in a nested run, mlflow.projects.run() will have a parent_run_id. | test_run_with_parent | python | mlflow/mlflow | tests/projects/test_projects.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_projects.py | Apache-2.0 |
def test_conda_path(mock_env, expected_conda, expected_activate, monkeypatch):
"""Verify that we correctly determine the path to conda executables"""
monkeypatch.delenvs([CONDA_EXE, MLFLOW_CONDA_HOME.name], raising=False)
monkeypatch.setenvs(mock_env)
assert mlflow.utils.conda.get_conda_bin_executable("... | Verify that we correctly determine the path to conda executables | test_conda_path | python | mlflow/mlflow | tests/projects/test_projects.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_projects.py | Apache-2.0 |
def test_find_conda_executables(mock_env, expected_conda_env_create_path, monkeypatch):
"""
Verify that we correctly determine the path to executables to be used to
create environments (for example, it could be mamba instead of conda)
"""
monkeypatch.delenvs(
[CONDA_EXE, MLFLOW_CONDA_HOME.na... |
Verify that we correctly determine the path to executables to be used to
create environments (for example, it could be mamba instead of conda)
| test_find_conda_executables | python | mlflow/mlflow | tests/projects/test_projects.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_projects.py | Apache-2.0 |
def test_create_env_with_mamba(monkeypatch):
"""
Test that mamba is called when set, and that we fail when mamba is not available or is
not working. We mock the calls so we do not actually execute mamba (which is not
installed in the test environment anyway)
"""
def exec_cmd_mock(cmd, *args, **... |
Test that mamba is called when set, and that we fail when mamba is not available or is
not working. We mock the calls so we do not actually execute mamba (which is not
installed in the test environment anyway)
| test_create_env_with_mamba | python | mlflow/mlflow | tests/projects/test_projects.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_projects.py | Apache-2.0 |
def test_project_get_entry_point():
"""Test that `Project` correctly parses entry point information from an MLproject file."""
project = load_project()
entry_point = project.get_entry_point("greeter")
assert entry_point.name == "greeter"
assert entry_point.command == "python greeter.py {greeting} {n... | Test that `Project` correctly parses entry point information from an MLproject file. | test_project_get_entry_point | python | mlflow/mlflow | tests/projects/test_project_spec.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_project_spec.py | Apache-2.0 |
def test_project_get_unspecified_entry_point():
"""Test that `Project` can run Python & bash scripts directly as entry points"""
project = load_project()
entry_point = project.get_entry_point("my_script.py")
assert entry_point.name == "my_script.py"
assert entry_point.command == "python my_script.py... | Test that `Project` can run Python & bash scripts directly as entry points | test_project_get_unspecified_entry_point | python | mlflow/mlflow | tests/projects/test_project_spec.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_project_spec.py | Apache-2.0 |
def test_load_project(tmp_path, mlproject, conda_env_path, conda_env_contents, mlproject_path):
"""
Test that we can load a project with various combinations of an MLproject / conda.yaml file
"""
if mlproject:
tmp_path.joinpath(mlproject_path).write_text(mlproject)
if conda_env_path:
... |
Test that we can load a project with various combinations of an MLproject / conda.yaml file
| test_load_project | python | mlflow/mlflow | tests/projects/test_project_spec.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_project_spec.py | Apache-2.0 |
def test_storage_dir(tmp_path):
"""
Test that we correctly handle the `storage_dir` argument, which specifies where to download
distributed artifacts passed to arguments of type `path`.
"""
assert os.path.dirname(_get_storage_dir(tmp_path)) == str(tmp_path)
assert os.path.dirname(_get_storage_di... |
Test that we correctly handle the `storage_dir` argument, which specifies where to download
distributed artifacts passed to arguments of type `path`.
| test_storage_dir | python | mlflow/mlflow | tests/projects/test_utils.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_utils.py | Apache-2.0 |
def test_virtualenv_project_no_env_file(create_virtualenv_spy, tmp_path):
"""
When neither python_env.yaml nor conda.yaml is present, virtualenv should be used as an
environment manager.
"""
ml_project_file = tmp_path.joinpath("MLproject")
ml_project_file.write_text(
"""
name: test
entry... |
When neither python_env.yaml nor conda.yaml is present, virtualenv should be used as an
environment manager.
| test_virtualenv_project_no_env_file | python | mlflow/mlflow | tests/projects/test_virtualenv_projects.py | https://github.com/mlflow/mlflow/blob/master/tests/projects/test_virtualenv_projects.py | Apache-2.0 |
async def roulette_wheel(ctx: RunContext[int], square: int) -> str:
"""check if the square is a winner"""
return "winner" if square == ctx.deps else "loser" | check if the square is a winner | roulette_wheel | python | mlflow/mlflow | tests/pydantic_ai/test_pydanticai_fluent_tracing.py | https://github.com/mlflow/mlflow/blob/master/tests/pydantic_ai/test_pydanticai_fluent_tracing.py | Apache-2.0 |
def get_model_class():
"""
Defines a custom Python model class that wraps a scikit-learn estimator.
This can be invoked within a pytest fixture to define the class in the ``__main__`` scope.
Alternatively, it can be invoked within a module to define the class in the module's scope.
"""
from cust... |
Defines a custom Python model class that wraps a scikit-learn estimator.
This can be invoked within a pytest fixture to define the class in the ``__main__`` scope.
Alternatively, it can be invoked within a module to define the class in the module's scope.
| get_model_class | python | mlflow/mlflow | tests/pyfunc/test_inferred_code_path.py | https://github.com/mlflow/mlflow/blob/master/tests/pyfunc/test_inferred_code_path.py | Apache-2.0 |
def test_model_with_code_path_containing_main(tmp_path):
"""Test that the __main__ module is unaffected by model loading"""
directory = tmp_path.joinpath("model_with_main")
directory.mkdir()
main = directory.joinpath("__main__.py")
main.write_text("# empty main")
with mlflow.start_run():
... | Test that the __main__ module is unaffected by model loading | test_model_with_code_path_containing_main | python | mlflow/mlflow | tests/pyfunc/test_model_export_with_class_and_artifacts.py | https://github.com/mlflow/mlflow/blob/master/tests/pyfunc/test_model_export_with_class_and_artifacts.py | Apache-2.0 |
def _compare_exact_tensor_dict_input(d1, d2):
"""Return whether two dicts of np arrays are exactly equal"""
if d1.keys() != d2.keys():
return False
return all(np.array_equal(d1[key], d2[key]) for key in d1) | Return whether two dicts of np arrays are exactly equal | _compare_exact_tensor_dict_input | python | mlflow/mlflow | tests/pyfunc/test_pyfunc_schema_enforcement.py | https://github.com/mlflow/mlflow/blob/master/tests/pyfunc/test_pyfunc_schema_enforcement.py | Apache-2.0 |
def test_python_model_serving_compatible(tmp_path):
"""
# Code for logging the model in mlflow 2.4.0
import mlflow
from mlflow.models import infer_signature
class MyModel(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input):
return model_input
with mlflow.sta... |
# Code for logging the model in mlflow 2.4.0
import mlflow
from mlflow.models import infer_signature
class MyModel(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input):
return model_input
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
... | test_python_model_serving_compatible | python | mlflow/mlflow | tests/pyfunc/test_pyfunc_schema_enforcement.py | https://github.com/mlflow/mlflow/blob/master/tests/pyfunc/test_pyfunc_schema_enforcement.py | Apache-2.0 |
def test_function_python_model_serving_compatible(tmp_path):
"""
# Code for logging the model in mlflow 2.4.0
import mlflow
from mlflow.models import infer_signature
def my_model(model_input):
return model_input
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
... |
# Code for logging the model in mlflow 2.4.0
import mlflow
from mlflow.models import infer_signature
def my_model(model_input):
return model_input
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
python_model = my_model,
artifa... | test_function_python_model_serving_compatible | python | mlflow/mlflow | tests/pyfunc/test_pyfunc_schema_enforcement.py | https://github.com/mlflow/mlflow/blob/master/tests/pyfunc/test_pyfunc_schema_enforcement.py | Apache-2.0 |
def test_spark_udf_compatible_with_mlflow_2_4_0(tmp_path, spark):
"""
# Code for logging the model in mlflow 2.4.0
import mlflow
class TestModel(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input):
return ["string"] * len(model_input)
signature = mlflow.models.i... |
# Code for logging the model in mlflow 2.4.0
import mlflow
class TestModel(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input):
return ["string"] * len(model_input)
signature = mlflow.models.infer_signature(["input"])
with mlflow.start_run() as run:
mlf... | test_spark_udf_compatible_with_mlflow_2_4_0 | python | mlflow/mlflow | tests/pyfunc/test_spark.py | https://github.com/mlflow/mlflow/blob/master/tests/pyfunc/test_spark.py | Apache-2.0 |
def save_model_with_latest_mlflow_version(flavor, extra_pip_requirements=None, **kwargs):
"""
Save a model with overriding MLflow version from dev version to the latest released version.
By default a model is saved with the dev version of MLflow, which is not available on PyPI.
Usually we can be workaro... |
Save a model with overriding MLflow version from dev version to the latest released version.
By default a model is saved with the dev version of MLflow, which is not available on PyPI.
Usually we can be workaround this by adding --serve-wheel flag that starts local PyPI server,
however, this doesn't wo... | save_model_with_latest_mlflow_version | python | mlflow/mlflow | tests/pyfunc/docker/conftest.py | https://github.com/mlflow/mlflow/blob/master/tests/pyfunc/docker/conftest.py | Apache-2.0 |
def get_subclassed_model_definition():
"""
Defines a PyTorch model class that inherits from ``torch.nn.Module``. This method can be invoked
within a pytest fixture to define the model class in the ``__main__`` scope. Alternatively, it
can be invoked within a module to define the class in the module's sc... |
Defines a PyTorch model class that inherits from ``torch.nn.Module``. This method can be invoked
within a pytest fixture to define the model class in the ``__main__`` scope. Alternatively, it
can be invoked within a module to define the class in the module's scope.
| get_subclassed_model_definition | python | mlflow/mlflow | tests/pytorch/test_pytorch_model_export.py | https://github.com/mlflow/mlflow/blob/master/tests/pytorch/test_pytorch_model_export.py | Apache-2.0 |
def main_scoped_subclassed_model(data):
"""
A custom PyTorch model inheriting from ``torch.nn.Module`` whose class is defined in the
"__main__" scope.
"""
model_class = get_subclassed_model_definition()
model = model_class()
train_model(model=model, data=data)
return model |
A custom PyTorch model inheriting from ``torch.nn.Module`` whose class is defined in the
"__main__" scope.
| main_scoped_subclassed_model | python | mlflow/mlflow | tests/pytorch/test_pytorch_model_export.py | https://github.com/mlflow/mlflow/blob/master/tests/pytorch/test_pytorch_model_export.py | Apache-2.0 |
def module_scoped_subclassed_model(data):
"""
A custom PyTorch model inheriting from ``torch.nn.Module`` whose class is defined in the test
module scope.
"""
model = ModuleScopedSubclassedModel()
train_model(model=model, data=data)
return model |
A custom PyTorch model inheriting from ``torch.nn.Module`` whose class is defined in the test
module scope.
| module_scoped_subclassed_model | python | mlflow/mlflow | tests/pytorch/test_pytorch_model_export.py | https://github.com/mlflow/mlflow/blob/master/tests/pytorch/test_pytorch_model_export.py | Apache-2.0 |
def test_load_pyfunc_succeeds_when_data_is_model_file_instead_of_directory(
module_scoped_subclassed_model, model_path, data
):
"""
This test verifies that PyTorch models saved in older versions of MLflow are loaded successfully
by ``mlflow.pytorch.load_model``. The ``data`` path associated with these o... |
This test verifies that PyTorch models saved in older versions of MLflow are loaded successfully
by ``mlflow.pytorch.load_model``. The ``data`` path associated with these older models is
serialized PyTorch model file, as opposed to the current format: a directory containing a
serialized model file and ... | test_load_pyfunc_succeeds_when_data_is_model_file_instead_of_directory | python | mlflow/mlflow | tests/pytorch/test_pytorch_model_export.py | https://github.com/mlflow/mlflow/blob/master/tests/pytorch/test_pytorch_model_export.py | Apache-2.0 |
def test_save_state_dict_can_save_nested_state_dict(model_path):
"""
This test ensures that `save_state_dict` supports a use case described in the page below
where a user bundles multiple objects (e.g., model, optimizer, learning-rate scheduler)
into a single nested state_dict and loads it back later fo... |
This test ensures that `save_state_dict` supports a use case described in the page below
where a user bundles multiple objects (e.g., model, optimizer, learning-rate scheduler)
into a single nested state_dict and loads it back later for inference or re-training:
https://pytorch.org/tutorials/recipes/re... | test_save_state_dict_can_save_nested_state_dict | python | mlflow/mlflow | tests/pytorch/test_pytorch_model_export.py | https://github.com/mlflow/mlflow/blob/master/tests/pytorch/test_pytorch_model_export.py | Apache-2.0 |
def to_dict(self) -> dict[str, str]:
"""
Returns:
A string dictionary containing the following fields: name,
digest, source, source type, schema (optional), profile
(optional).
"""
config = super().to_dict()
config.update(
{
... |
Returns:
A string dictionary containing the following fields: name,
digest, source, source type, schema (optional), profile
(optional).
| to_dict | python | mlflow/mlflow | tests/resources/data/dataset.py | https://github.com/mlflow/mlflow/blob/master/tests/resources/data/dataset.py | Apache-2.0 |
def before_req_hook():
"""A custom before request handler.
Can implement things such as authentication, special handling, etc.
"""
if not is_logged_in():
app_logger.warning("Hello from before request!")
return "Unauthorized", 403 | A custom before request handler.
Can implement things such as authentication, special handling, etc.
| before_req_hook | python | mlflow/mlflow | tests/resources/mlflow-test-plugin/mlflow_test_plugin/app.py | https://github.com/mlflow/mlflow/blob/master/tests/resources/mlflow-test-plugin/mlflow_test_plugin/app.py | Apache-2.0 |
def _to_dict(self, base_dict: dict[str, str]) -> dict[str, str]:
"""
Args:
base_dict: A string dictionary of base information about the
dataset, including: name, digest, source, and source type.
Returns:
A string dictionary containing the following fields... |
Args:
base_dict: A string dictionary of base information about the
dataset, including: name, digest, source, and source type.
Returns:
A string dictionary containing the following fields: name,
digest, source, source type, schema (optional), profile
... | _to_dict | python | mlflow/mlflow | tests/resources/mlflow-test-plugin/mlflow_test_plugin/dummy_dataset.py | https://github.com/mlflow/mlflow/blob/master/tests/resources/mlflow-test-plugin/mlflow_test_plugin/dummy_dataset.py | Apache-2.0 |
def fail_transform_job_creations(self, operation_name, operation_kwargs):
"""
Processes all boto3 client operations according to the following rules:
- If the operation is a transform job creation, create the transform job and
set its status to ``TransformJob.STATUS_FAILED``.
-... |
Processes all boto3 client operations according to the following rules:
- If the operation is a transform job creation, create the transform job and
set its status to ``TransformJob.STATUS_FAILED``.
- Else, execute the client operation as normal
| fail_transform_job_creations | python | mlflow/mlflow | tests/sagemaker/test_batch_deployment.py | https://github.com/mlflow/mlflow/blob/master/tests/sagemaker/test_batch_deployment.py | Apache-2.0 |
def fail_endpoint_creations(self, operation_name, operation_kwargs):
"""
Processes all boto3 client operations according to the following rules:
- If the operation is an endpoint creation, create the endpoint and set its status to
``Endpoint.STATUS_FAILED``.
- Else, execute the... |
Processes all boto3 client operations according to the following rules:
- If the operation is an endpoint creation, create the endpoint and set its status to
``Endpoint.STATUS_FAILED``.
- Else, execute the client operation as normal
| fail_endpoint_creations | python | mlflow/mlflow | tests/sagemaker/test_sagemaker_deployment_client.py | https://github.com/mlflow/mlflow/blob/master/tests/sagemaker/test_sagemaker_deployment_client.py | Apache-2.0 |
def fail_endpoint_updates(self, operation_name, operation_kwargs):
"""
Processes all boto3 client operations according to the following rules:
- If the operation is an endpoint update, update the endpoint and set its status to
``Endpoint.STATUS_FAILED``.
- Else, execute the cli... |
Processes all boto3 client operations according to the following rules:
- If the operation is an endpoint update, update the endpoint and set its status to
``Endpoint.STATUS_FAILED``.
- Else, execute the client operation as normal
| fail_endpoint_updates | python | mlflow/mlflow | tests/sagemaker/test_sagemaker_deployment_client.py | https://github.com/mlflow/mlflow/blob/master/tests/sagemaker/test_sagemaker_deployment_client.py | Apache-2.0 |
def validate_deletes(self, operation_name, operation_kwargs):
"""
Processes all boto3 client operations according to the following rules:
- If the operation deletes an S3 or SageMaker resource, ensure that the deletion was
initiated after the completion of the endpoint update
-... |
Processes all boto3 client operations according to the following rules:
- If the operation deletes an S3 or SageMaker resource, ensure that the deletion was
initiated after the completion of the endpoint update
- Else, execute the client operation as normal
| validate_deletes | python | mlflow/mlflow | tests/sagemaker/test_sagemaker_deployment_client.py | https://github.com/mlflow/mlflow/blob/master/tests/sagemaker/test_sagemaker_deployment_client.py | Apache-2.0 |
def create_endpoint_config(self):
"""
Handler for the SageMaker "CreateEndpointConfig" API call documented here:
https://docs.aws.amazon.com/sagemaker/latest/dg/API_CreateEndpointConfig.html.
"""
config_name = self.request_params["EndpointConfigName"]
production_variants ... |
Handler for the SageMaker "CreateEndpointConfig" API call documented here:
https://docs.aws.amazon.com/sagemaker/latest/dg/API_CreateEndpointConfig.html.
| create_endpoint_config | python | mlflow/mlflow | tests/sagemaker/mock/__init__.py | https://github.com/mlflow/mlflow/blob/master/tests/sagemaker/mock/__init__.py | Apache-2.0 |
def describe_endpoint_config(self):
"""
Handler for the SageMaker "DescribeEndpoint" API call documented here:
https://docs.aws.amazon.com/sagemaker/latest/dg/API_DescribeEndpoint.html.
"""
config_name = self.request_params["EndpointConfigName"]
config_description = self.... |
Handler for the SageMaker "DescribeEndpoint" API call documented here:
https://docs.aws.amazon.com/sagemaker/latest/dg/API_DescribeEndpoint.html.
| describe_endpoint_config | python | mlflow/mlflow | tests/sagemaker/mock/__init__.py | https://github.com/mlflow/mlflow/blob/master/tests/sagemaker/mock/__init__.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.