From f378702eb409b41bdc12bdc4f58e1d2cf66c0409 Mon Sep 17 00:00:00 2001 From: Ingmar Schoegl Date: Mon, 29 Jun 2020 22:53:23 -0500 Subject: [PATCH] [AnyMap] add non-const version of AnyMap::at --- include/cantera/base/AnyMap.h | 1 + src/base/AnyMap.cpp | 10 ++++++++++ test/thermo/thermoFromYaml.cpp | 12 ++++++++++++ 3 files changed, 23 insertions(+) diff --git a/include/cantera/base/AnyMap.h b/include/cantera/base/AnyMap.h index 27f4a173831..9511d36e15e 100644 --- a/include/cantera/base/AnyMap.h +++ b/include/cantera/base/AnyMap.h @@ -370,6 +370,7 @@ class AnyMap //! Get the value of the item stored in `key`. Raises an exception if the //! value does not exist. + AnyValue& at(const std::string& key); const AnyValue& at(const std::string& key) const; //! Returns `true` if the map contains an item named `key`. diff --git a/src/base/AnyMap.cpp b/src/base/AnyMap.cpp index b070038ed32..de8d8b5605f 100644 --- a/src/base/AnyMap.cpp +++ b/src/base/AnyMap.cpp @@ -958,6 +958,16 @@ const AnyValue& AnyMap::operator[](const std::string& key) const } } +AnyValue& AnyMap::at(const std::string& key) +{ + try { + return m_data.at(key); + } catch (std::out_of_range&) { + throw InputFileError("AnyMap::at", *this, + "Key '{}' not found.\nExisting keys: {}", key, keys_str()); + } +} + const AnyValue& AnyMap::at(const std::string& key) const { try { diff --git a/test/thermo/thermoFromYaml.cpp b/test/thermo/thermoFromYaml.cpp index b3f3a3024eb..2980d2354fa 100644 --- a/test/thermo/thermoFromYaml.cpp +++ b/test/thermo/thermoFromYaml.cpp @@ -1,4 +1,5 @@ #include "gtest/gtest.h" +#include "gmock/gmock.h" #include "cantera/thermo/ThermoFactory.h" #include "cantera/thermo/Elements.h" #include "cantera/thermo/MolalityVPSSTP.h" @@ -26,6 +27,17 @@ TEST(ThermoFromYaml, simpleIdealGas) EXPECT_DOUBLE_EQ(thermo.cp_mass(), 1037.7546065787594); } +TEST(ThermoFromYaml, missingKey) +{ + AnyMap root = AnyMap::fromYamlFile("ideal-gas.yaml"); + try { + AnyMap& map = root.at("spam").getMapWhere("name", "unknown"); + EXPECT_TRUE(map["name"].hasMapWhere("foo", "bar")); + } catch (std::exception& ex) { + EXPECT_THAT(ex.what(), ::testing::HasSubstr("Key 'spam' not found.")); + } +} + TEST(ThermoFromYaml, failDuplicateSpecies) { EXPECT_THROW(newThermo("ideal-gas.yaml", "duplicate-species"), CanteraError);