|
| 1 | +# License: MIT |
| 2 | +# Copyright © 2024 Frequenz Energy-as-a-Service GmbH |
| 3 | + |
| 4 | +"""Tests for the config utilities.""" |
| 5 | + |
| 6 | +import dataclasses |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +import marshmallow |
| 10 | +import marshmallow_dataclass |
| 11 | +import pytest |
| 12 | +from pytest_mock import MockerFixture |
| 13 | + |
| 14 | +from frequenz.sdk.config._util import load_config |
| 15 | + |
| 16 | + |
| 17 | +@dataclasses.dataclass |
| 18 | +class SimpleConfig: |
| 19 | + """A simple configuration class for testing.""" |
| 20 | + |
| 21 | + name: str |
| 22 | + value: int |
| 23 | + |
| 24 | + |
| 25 | +@marshmallow_dataclass.dataclass |
| 26 | +class MmSimpleConfig: |
| 27 | + """A simple configuration class for testing.""" |
| 28 | + |
| 29 | + name: str = dataclasses.field(metadata={"validate": lambda s: s.startswith("test")}) |
| 30 | + value: int |
| 31 | + |
| 32 | + |
| 33 | +def test_load_config_dataclass() -> None: |
| 34 | + """Test that load_config loads a configuration into a configuration class.""" |
| 35 | + config: dict[str, Any] = {"name": "test", "value": 42} |
| 36 | + |
| 37 | + loaded_config = load_config(SimpleConfig, config) |
| 38 | + assert loaded_config == SimpleConfig(name="test", value=42) |
| 39 | + |
| 40 | + config["name"] = "not test" |
| 41 | + loaded_config = load_config(SimpleConfig, config) |
| 42 | + assert loaded_config == SimpleConfig(name="not test", value=42) |
| 43 | + |
| 44 | + |
| 45 | +def test_load_config_marshmallow_dataclass() -> None: |
| 46 | + """Test that load_config loads a configuration into a configuration class.""" |
| 47 | + config: dict[str, Any] = {"name": "test", "value": 42} |
| 48 | + loaded_config = load_config(MmSimpleConfig, config) |
| 49 | + assert loaded_config == MmSimpleConfig(name="test", value=42) |
| 50 | + |
| 51 | + config["name"] = "not test" |
| 52 | + with pytest.raises(marshmallow.ValidationError): |
| 53 | + _ = load_config(MmSimpleConfig, config) |
| 54 | + |
| 55 | + |
| 56 | +def test_load_config_type_hints(mocker: MockerFixture) -> None: |
| 57 | + """Test that load_config loads a configuration into a configuration class.""" |
| 58 | + mock_class_schema = mocker.Mock() |
| 59 | + mock_class_schema.return_value.load.return_value = {"name": "test", "value": 42} |
| 60 | + mocker.patch( |
| 61 | + "frequenz.sdk.config._util.class_schema", return_value=mock_class_schema |
| 62 | + ) |
| 63 | + config: dict[str, Any] = {} |
| 64 | + |
| 65 | + # We add the type hint to test that the return type (hint) is correct |
| 66 | + _: MmSimpleConfig = load_config(MmSimpleConfig, config, marshmallow_arg=1) |
| 67 | + mock_class_schema.return_value.load.assert_called_once_with( |
| 68 | + config, marshmallow_arg=1 |
| 69 | + ) |
0 commit comments