Ignore clearing of invalid user config keys

This commit is contained in:
Jeremy Stretch 2020-04-29 15:05:29 -04:00
parent 3b6d9dc552
commit f8060ce112
3 changed files with 7 additions and 6 deletions

View File

@ -108,7 +108,7 @@ class UserConfig(models.Model):
userconfig.clear('foo.bar.baz') userconfig.clear('foo.bar.baz')
A KeyError is raised in the event any key along the path does not exist. Invalid keys will be ignored silently.
:param path: Dotted path to the configuration key. For example, 'foo.bar' deletes self.data['foo']['bar']. :param path: Dotted path to the configuration key. For example, 'foo.bar' deletes self.data['foo']['bar'].
:param commit: If true, the UserConfig instance will be saved once the new value has been applied. :param commit: If true, the UserConfig instance will be saved once the new value has been applied.
@ -117,11 +117,13 @@ class UserConfig(models.Model):
keys = path.split('.') keys = path.split('.')
for key in keys[:-1]: for key in keys[:-1]:
if key in d and type(d[key]) is dict: if key not in d:
break
if type(d[key]) is dict:
d = d[key] d = d[key]
key = keys[-1] key = keys[-1]
del(d[key]) d.pop(key, None) # Avoid a KeyError on invalid keys
if commit: if commit:
self.save() self.save()

View File

View File

@ -104,6 +104,5 @@ class UserConfigTest(TestCase):
self.assertTrue('foo' not in userconfig.data['b']) self.assertTrue('foo' not in userconfig.data['b'])
self.assertEqual(userconfig.data['b']['bar'], 102) self.assertEqual(userconfig.data['b']['bar'], 102)
# Clear an invalid value # Clear a non-existing value; should fail silently
with self.assertRaises(KeyError): userconfig.clear('invalid')
userconfig.clear('invalid')