diff --git a/pywr-core/src/lib.rs b/pywr-core/src/lib.rs index 2a6bcf01..7220c577 100644 --- a/pywr-core/src/lib.rs +++ b/pywr-core/src/lib.rs @@ -179,6 +179,8 @@ pub enum PywrError { NetworkNotFound(String), #[error("network index ({0}) not found")] NetworkIndexNotFound(usize), + #[error("network name `{0}` already exists.")] + NetworkNameAlreadyExists(String), #[error("parameters do not provide an initial value")] ParameterNoInitialValue, #[error("parameter state not found for parameter index {0}")] diff --git a/pywr-core/src/models/multi.rs b/pywr-core/src/models/multi.rs index a9568338..863295cb 100644 --- a/pywr-core/src/models/multi.rs +++ b/pywr-core/src/models/multi.rs @@ -114,8 +114,12 @@ impl MultiNetworkModel { .ok_or(PywrError::NetworkNotFound(name.to_string())) } - pub fn add_network(&mut self, name: &str, network: Network) -> usize { - // TODO check for duplicate names + /// Add a [`Network`] to the model. The name must be unique. + pub fn add_network(&mut self, name: &str, network: Network) -> Result { + if self.get_network_index_by_name(name).is_ok() { + return Err(PywrError::NetworkNameAlreadyExists(name.to_string())); + } + let idx = self.networks.len(); self.networks.push(MultiNetworkEntry { name: name.to_string(), @@ -123,7 +127,7 @@ impl MultiNetworkModel { parameters: Vec::new(), }); - idx + Ok(idx) } /// Add a transfer of data from one network to another. @@ -392,4 +396,19 @@ mod tests { multi_model.step(&mut state).expect("Failed to step multi1-model.") } + + #[test] + fn test_duplicate_network_names() { + let timestepper = default_timestepper(); + let scenario_collection = ScenarioGroupCollection::default(); + + let mut multi_model = MultiNetworkModel::new(ModelDomain::from(timestepper, scenario_collection).unwrap()); + + let network = Network::default(); + let _network1_idx = multi_model.add_network("network1", network); + let network = Network::default(); + let result = multi_model.add_network("network1", network); + + assert!(result.is_err()); + } }