Skip to content

Commit

Permalink
[AnyMap] add non-const version of AnyMap::at
Browse files Browse the repository at this point in the history
  • Loading branch information
ischoegl committed Jun 30, 2020
1 parent 5ac80b4 commit f378702
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
1 change: 1 addition & 0 deletions include/cantera/base/AnyMap.h
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
10 changes: 10 additions & 0 deletions src/base/AnyMap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
12 changes: 12 additions & 0 deletions test/thermo/thermoFromYaml.cpp
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit f378702

Please sign in to comment.