Skip to content

Commit

Permalink
test: create and update tests for fuel consumer
Browse files Browse the repository at this point in the history
  • Loading branch information
frodehk committed Jan 10, 2025
1 parent ade417b commit 8189b46
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 48 deletions.
9 changes: 3 additions & 6 deletions src/libecalc/presentation/yaml/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from libecalc.common.time_utils import Frequency, Period
from libecalc.common.variables import ExpressionEvaluator, VariablesMap
from libecalc.domain.infrastructure.energy_components.component_validation_error import (
ComponentDtoValidationError,
ComponentValidationException,
)
from libecalc.dto import ResultOptions
Expand Down Expand Up @@ -112,10 +111,8 @@ def dto(self):
references=self._get_reference_service(),
target_period=self.period,
)
try:
return model_mapper.from_yaml_to_dto(configuration=self._configuration)
except ComponentValidationException as e:
raise ComponentDtoValidationError(errors=e.errors()) from e

return model_mapper.from_yaml_to_dto(configuration=self._configuration)

@property
def period(self) -> Period:
Expand Down Expand Up @@ -218,5 +215,5 @@ def validate_for_run(self) -> Self:
# Validate and create the graph used for evaluating the energy model
self.get_graph()
return self
except DtoValidationError as e:
except (DtoValidationError, ComponentValidationException) as e:
raise ModelValidationException(errors=e.errors()) from e
12 changes: 6 additions & 6 deletions tests/libecalc/core/consumers/system/test_system_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,9 +329,9 @@ def test_assemble_operational_setting_from_model_result_list():
operational_settings=operational_settings, setting_number_used_per_timestep=setting_number_used_per_timestep
)

assert np.array(result.rates[0]).tolist() == [0, 31, 22, 13, 4]
assert np.array(result.rates[1]).tolist() == [0, 31, 22, 13, 4]
assert np.array(result.suction_pressures[0]).tolist() == [0, 31, 22, 13, 4]
assert np.array(result.suction_pressures[1]).tolist() == [0, 31, 22, 13, 4]
assert np.array(result.discharge_pressures[0]).tolist() == [0, 31, 22, 13, 4]
assert np.array(result.discharge_pressures[1]).tolist() == [0, 31, 22, 13, 4]
assert result.rates[0] == [0, 31, 22, 13, 4]
assert result.rates[1] == [0, 31, 22, 13, 4]
assert result.suction_pressures[0] == [0, 31, 22, 13, 4]
assert result.suction_pressures[1] == [0, 31, 22, 13, 4]
assert result.discharge_pressures[0] == [0, 31, 22, 13, 4]
assert result.discharge_pressures[1] == [0, 31, 22, 13, 4]
105 changes: 69 additions & 36 deletions tests/libecalc/dto/test_fuel_consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
from io import StringIO

import pytest
from yaml import YAMLError

from libecalc.presentation.yaml.validation_errors import DtoValidationError, DataValidationError, ValidationError
from libecalc.presentation.yaml.yaml_models.exceptions import DuplicateKeyError, YamlError
import libecalc.dto.fuel_type
import libecalc.dto.types
from ecalc_cli.types import Frequency
Expand All @@ -18,8 +21,10 @@
ComponentDtoValidationError,
)
from libecalc.expression import Expression
from libecalc.presentation.yaml.model_validation_exception import ModelValidationException
from libecalc.presentation.yaml.yaml_entities import ResourceStream
from libecalc.presentation.yaml.yaml_models.pyyaml_yaml_model import PyYamlYamlModel
from libecalc.presentation.yaml.yaml_types.components.yaml_asset import YamlAsset
from libecalc.testing.yaml_builder import YamlAssetBuilder, YamlInstallationBuilder, YamlFuelConsumerBuilder

regularity = {Period(datetime(2000, 1, 1)): Expression.setup_from_expression(1)}
Expand Down Expand Up @@ -101,56 +106,84 @@ def get_fuel_consumer(
)


class TestFuelConsumer:
def test_missing_fuel(self):
with pytest.raises(ComponentValidationException) as exc_info:
FuelConsumer(
name="test",
fuel={},
component_type=ComponentType.GENERIC,
energy_usage_model={
Period(datetime(2000, 1, 1)): dto.DirectConsumerFunction(
fuel_rate=Expression.setup_from_expression(1),
energy_usage_type=EnergyUsageType.FUEL,
)
},
regularity=regularity,
user_defined_category="category",
)
assert "Name: test\nMessage: Missing fuel for fuel consumer" in str(exc_info.value.errors()[0])

def test_blank_fuel_name_and_missing_fuel(self, yaml_model_factory, request):
time_vector = [datetime(2027, 1, 1), datetime(2028, 1, 1), datetime(2029, 1, 1)]
variables = VariablesMap(time_vector=time_vector, variables={})
class TestFuelConsumerHelper:
def __init__(self):
self.time_vector = [datetime(2027, 1, 1), datetime(2028, 1, 1), datetime(2029, 1, 1)]
self.defined_fuel = "fuel"

fuel_consumer = YamlFuelConsumerBuilder().with_test_data().validate()

# Setting fuel reference name to blank
fuel_consumer.fuel = ""
def get_stream(self, consumer_fuel: str, installation_fuel: str = ""):
fuel_reference = consumer_fuel
fuel_consumer = YamlFuelConsumerBuilder().with_test_data().with_fuel(fuel_reference).validate()

installation = (
YamlInstallationBuilder().with_name("Installation 1").with_fuel_consumers([fuel_consumer])
YamlInstallationBuilder()
.with_name("Installation 1")
.with_fuel(installation_fuel)
.with_fuel_consumers([fuel_consumer])
).validate()

# No fuel is set for the asset (means None)
asset = (
YamlAssetBuilder().with_installations([installation]).with_start(time_vector[0]).with_end(time_vector[-1])
YamlAssetBuilder()
.with_test_data()
.with_installations([installation])
.with_start(self.time_vector[0])
.with_end(self.time_vector[-1])
).validate()

yaml_model_factory = request.getfixturevalue("yaml_model_factory")
# Set the name of defined fuel type for the asset
asset.fuel_types[0].name = self.defined_fuel

asset_dict = asset.model_dump(
serialize_as_any=True,
mode="json",
exclude_unset=True,
by_alias=True,
)

yaml_string = PyYamlYamlModel.dump_yaml(yaml_dict=asset_dict)
stream = ResourceStream(name="", stream=StringIO(yaml_string))
return ResourceStream(name="", stream=StringIO(yaml_string))


@pytest.fixture()
def test_fuel_consumer_helper():
return TestFuelConsumerHelper()


class TestFuelConsumer:
def test_blank_fuel_reference(self, yaml_model_factory, test_fuel_consumer_helper):
"""
Check scenarios with blank fuel reference.
The asset has one correctly defined fuel type, named 'fuel'.
"""

# Blank fuel reference in installation and in consumer
asset_stream = test_fuel_consumer_helper.get_stream(installation_fuel="", consumer_fuel="")

with pytest.raises(DataValidationError) as exc_info:
yaml_model_factory(resource_stream=asset_stream, resources={}, frequency=Frequency.YEAR).validate_for_run()

assert "Invalid fuel reference ''. Available references: fuel" in str(exc_info.value)

# Correct fuel reference in installation and blank in consumer.
# The installation fuel should propagate to the consumer, hence model should validate.
asset_stream = test_fuel_consumer_helper.get_stream(
installation_fuel=test_fuel_consumer_helper.defined_fuel, consumer_fuel=""
)

yaml_model_factory(resource_stream=asset_stream, resources={}, frequency=Frequency.YEAR).validate_for_run()

def test_wrong_fuel_reference(self, request, yaml_model_factory, test_fuel_consumer_helper):
"""
Check wrong fuel reference.
The asset has one correctly defined fuel type, named 'fuel'.
A wrong fuel reference can be caused by misspelling or by using a reference that is not defined in the asset FUEL_TYPES.
"""

asset_stream = test_fuel_consumer_helper.get_stream(
installation_fuel="wrong_fuel_name", consumer_fuel="wrong_fuel_name"
)

asset_yaml = yaml_model_factory(resource_stream=stream, resources={}, frequency=Frequency.YEAR)
energy_calculator = EnergyCalculator(energy_model=asset_yaml, expression_evaluator=variables)
with pytest.raises(DataValidationError) as exc_info:
yaml_model_factory(resource_stream=asset_stream, resources={}, frequency=Frequency.YEAR).validate_for_run()

with pytest.raises(ComponentDtoValidationError) as exc_info:
energy_calculator.evaluate_energy_usage()
assert "Name: flare\nMessage: Missing fuel for fuel consumer" in str(exc_info.value.errors[0])
assert "Invalid fuel reference 'wrong_fuel_name'. Available references: fuel" in str(exc_info.value)

0 comments on commit 8189b46

Please sign in to comment.