Skip to content

Commit

Permalink
Add validation for new Fever attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
noracato committed Jan 2, 2024
1 parent edbb596 commit 79a6603
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
40 changes: 40 additions & 0 deletions lib/atlas/node_attributes/fever.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ module NodeAttributes
# calculation.
class Fever
include ValueObject
include ActiveModel::Validations

values do
attribute :type, Symbol
Expand Down Expand Up @@ -36,12 +37,51 @@ class Fever
attribute :capacity, Hash[Symbol => Float]
end

validates :type, inclusion: %i[consumer producer]

validates_presence_of :share_in_group,
if: ->(mod) { mod.type == :producer },
message: 'must be set for producers'

validates_presence_of :technology_curve_type,
if: ->(mod) { mod.type == :producer },
message: 'must be set for producers'

validates :technology_curve_type,
inclusion: { in: ->(mod) { mod.class.technology_types } }

validates_presence_of :curve,
if: ->(mod) { mod.type == :consumer },
message: 'must be set for consumers'

validate :validate_curve_types

def to_hash
hash = super
hash.delete(:capacity) if hash[:capacity].empty?

hash
end

def self.technology_types
@technology_types ||= %i[tech_day_night tech_constant].freeze
end

def validate_curve_types
return unless type == :consumer

unless curve.is_a?(Hash)
errors.add(
:curve,
'must consist of a definition for each technology curve type, e.g. curve.tech_day_night'
)
return
end

if curve.keys.any? { |key| !Fever.technology_types.include?(key) }
errors.add(:curve, "keys must be one of #{Fever.technology_types}")
end
end
end
end
end
28 changes: 28 additions & 0 deletions spec/atlas/node_attributes/fever_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# frozen_string_literal: true

require 'spec_helper'

describe Atlas::NodeAttributes::Fever do
describe '#curve for consumer nodes' do
context 'when the curve is not a hash' do
it 'has an error' do
mo = described_class.new(type: :consumer, curve: :households_heating)
expect(mo.errors_on(:curve)).to include('must consist of a definition for each technology curve type, e.g. curve.tech_day_night')
end
end

context 'when one curve key is not valid' do
it 'has an error' do
mo = described_class.new(type: :consumer, curve: {tech_nope: :households_heating })
expect(mo.errors_on(:curve)).to include('keys must be one of [:tech_day_night, :tech_constant]')
end
end

context 'when no curve is specified' do
it 'has an error' do
mo = described_class.new(type: :consumer)
expect(mo.errors_on(:curve)).to include('must be set for consumers')
end
end
end
end

0 comments on commit 79a6603

Please sign in to comment.