|
| 1 | +# License: MIT |
| 2 | +# Copyright © 2024 Frequenz Energy-as-a-Service GmbH |
| 3 | + |
| 4 | +"""Tests for machine learning model manager.""" |
| 5 | + |
| 6 | +import pickle |
| 7 | +from dataclasses import dataclass |
| 8 | +from pathlib import Path |
| 9 | +from typing import Any |
| 10 | +from unittest.mock import AsyncMock, MagicMock, mock_open, patch |
| 11 | + |
| 12 | +import pytest |
| 13 | + |
| 14 | +from frequenz.sdk.ml import ModelManager |
| 15 | + |
| 16 | + |
| 17 | +@dataclass |
| 18 | +class MockModel: |
| 19 | + """Mock model for unit testing purposes.""" |
| 20 | + |
| 21 | + data: int | str |
| 22 | + |
| 23 | + def predict(self) -> int | str: |
| 24 | + """Make a prediction based on the model data.""" |
| 25 | + return self.data |
| 26 | + |
| 27 | + |
| 28 | +async def test_model_manager_loading() -> None: |
| 29 | + """Test loading models using ModelManager with direct configuration.""" |
| 30 | + model1 = MockModel("Model 1 Data") |
| 31 | + model2 = MockModel("Model 2 Data") |
| 32 | + pickled_model1 = pickle.dumps(model1) |
| 33 | + pickled_model2 = pickle.dumps(model2) |
| 34 | + |
| 35 | + model_paths = { |
| 36 | + "model1": Path("path/to/model1.pkl"), |
| 37 | + "model2": Path("path/to/model2.pkl"), |
| 38 | + } |
| 39 | + |
| 40 | + mock_files = { |
| 41 | + "path/to/model1.pkl": mock_open(read_data=pickled_model1)(), |
| 42 | + "path/to/model2.pkl": mock_open(read_data=pickled_model2)(), |
| 43 | + } |
| 44 | + |
| 45 | + def mock_open_func(file_path: Path, *__args: Any, **__kwargs: Any) -> Any: |
| 46 | + """Mock open function to return the correct mock file object. |
| 47 | +
|
| 48 | + Args: |
| 49 | + file_path: The path to the file to open. |
| 50 | + *__args: Variable length argument list. This can be used to pass additional |
| 51 | + positional parameters typically used in file opening operations, |
| 52 | + such as `mode` or `buffering`. |
| 53 | + **__kwargs: Arbitrary keyword arguments. This can include parameters like |
| 54 | + `encoding` and `errors`, common in file opening operations. |
| 55 | +
|
| 56 | + Returns: |
| 57 | + Any: The mock file object. |
| 58 | +
|
| 59 | + Raises: |
| 60 | + FileNotFoundError: If the file path is not in the mock files dictionary. |
| 61 | + """ |
| 62 | + file_path_str = str(file_path) |
| 63 | + if file_path_str in mock_files: |
| 64 | + file_handle = MagicMock() |
| 65 | + file_handle.__enter__.return_value = mock_files[file_path_str] |
| 66 | + return file_handle |
| 67 | + raise FileNotFoundError(f"No mock setup for {file_path_str}") |
| 68 | + |
| 69 | + with patch("pathlib.Path.open", new=mock_open_func): |
| 70 | + with patch.object(Path, "exists", return_value=True): |
| 71 | + model_manager: ModelManager[MockModel] = ModelManager( |
| 72 | + model_paths=model_paths |
| 73 | + ) |
| 74 | + |
| 75 | + with patch( |
| 76 | + "frequenz.channels.file_watcher.FileWatcher", new_callable=AsyncMock |
| 77 | + ): |
| 78 | + model_manager.start() # Start the service |
| 79 | + |
| 80 | + assert isinstance(model_manager.get_model("model1"), MockModel) |
| 81 | + assert model_manager.get_model("model1").data == "Model 1 Data" |
| 82 | + assert model_manager.get_model("model2").data == "Model 2 Data" |
| 83 | + |
| 84 | + with pytest.raises(KeyError): |
| 85 | + model_manager.get_model("key3") |
| 86 | + |
| 87 | + await model_manager.stop() # Stop the service to clean up |
| 88 | + |
| 89 | + |
| 90 | +async def test_model_manager_update() -> None: |
| 91 | + """Test updating a model in ModelManager.""" |
| 92 | + original_model = MockModel("Original Data") |
| 93 | + updated_model = MockModel("Updated Data") |
| 94 | + pickled_original_model = pickle.dumps(original_model) |
| 95 | + pickled_updated_model = pickle.dumps(updated_model) |
| 96 | + |
| 97 | + model_paths = {"model1": Path("path/to/model1.pkl")} |
| 98 | + |
| 99 | + mock_file = mock_open(read_data=pickled_original_model) |
| 100 | + with ( |
| 101 | + patch("pathlib.Path.open", mock_file), |
| 102 | + patch.object(Path, "exists", return_value=True), |
| 103 | + ): |
| 104 | + model_manager = ModelManager[MockModel](model_paths=model_paths) |
| 105 | + with patch( |
| 106 | + "frequenz.channels.file_watcher.FileWatcher", new_callable=AsyncMock |
| 107 | + ): |
| 108 | + model_manager.start() # Start the service |
| 109 | + |
| 110 | + assert model_manager.get_model("model1").data == "Original Data" |
| 111 | + |
| 112 | + # Simulate updating the model file |
| 113 | + mock_file.return_value.read.return_value = pickled_updated_model |
| 114 | + with patch("pathlib.Path.open", mock_file): |
| 115 | + model_manager.reload_model(Path("path/to/model1.pkl")) |
| 116 | + assert model_manager.get_model("model1").data == "Updated Data" |
| 117 | + |
| 118 | + await model_manager.stop() # Stop the service to clean up |
0 commit comments