Unverified Commit a72ca2b7 authored by Jose Borreguero's avatar Jose Borreguero Committed by GitHub
Browse files

Merge pull request #32506 from mantidproject/configservice_get

New method "get" for the ConfigService class
parents 0df31440 ac63acc8
......@@ -50,6 +50,16 @@ const InstrumentInfo &getInstrument(ConfigServiceImpl &self, const object &name
return self.getInstrument(ExtractStdString(name)());
/// duck typing emulating dict.get method
std::string getStringUsingCacheElseDefault(ConfigServiceImpl &self, const std::string &key,
const std::string &defaultValue) {
std::vector<std::string> keys = self.keys();
if (self.hasProperty(key))
return self.getString(key, true);
return defaultValue;
// Ignore -Wconversion warnings coming from boost::python
// Seen with GCC 7.1.1 and Boost 1.63.0
......@@ -134,6 +144,12 @@ void export_ConfigService() {
.def("keys", &ConfigServiceImpl::keys, arg("self"))
// Treat this as a dictionary
.def("get", &getStringUsingCache, (arg("self"), arg("key")),
"get the string value of a property; return empty string value if the property "
"is not found in the configuration")
.def("get", &getStringUsingCacheElseDefault, (arg("self"), arg("key")), arg("default"),
"get the string value of a property; return a default string value if the property "
"is not found in the configuration")
.def("__getitem__", &getStringUsingCache, (arg("self"), arg("key")))
.def("__setitem__", &ConfigServiceImpl::setString, (arg("self"), arg("key"), arg("value")))
.def("__contains__", &ConfigServiceImpl::hasProperty, (arg("self"), arg("key")))
......@@ -64,17 +64,29 @@ class ConfigServiceTest(unittest.TestCase):
self.assertRaises(RuntimeError, config.getInstrument, "MadeUpInstrument")
def test_service_acts_like_dictionary(self):
dictcall = config.get("property_not_found")
self.assertEqual(dictcall, "")
test_prop = "projectRecovery.secondsBetween"
dictcall = config[test_prop]
fncall = config.getString(test_prop)
# Use brackets to retrieve a value
dictcall = config[test_prop]
self.assertEqual(dictcall, fncall)
self.assertNotEqual(config[test_prop], "")
# Use "get" to retrieve a value or a default
dictcall = config.get(test_prop, "other")
self.assertEqual(dictcall, fncall)
dictcall = config.get("property_not_found", "default_alternative")
self.assertEqual(dictcall, "default_alternative")
old_value = fncall
config.setString(test_prop, "1")
self.assertEqual(config.getString(test_prop), "1")
config[test_prop] = "2"
config[test_prop] = "2"
self.assertEqual(config.getString(test_prop), "2")
config.setString(test_prop, old_value)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment