Просмотр исходного кода

Ignore clearing of invalid user config keys

Jeremy Stretch 5 лет назад
Родитель
Сommit
f8060ce112
3 измененных файлов с 7 добавлено и 6 удалено
  1. 5 3
      netbox/users/models.py
  2. 0 0
      netbox/users/tests/__init__.py
  3. 2 3
      netbox/users/tests/test_models.py

+ 5 - 3
netbox/users/models.py

@@ -108,7 +108,7 @@ class UserConfig(models.Model):
 
             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 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('.')
 
         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]
 
         key = keys[-1]
-        del(d[key])
+        d.pop(key, None)  # Avoid a KeyError on invalid keys
 
         if commit:
             self.save()

+ 0 - 0
netbox/users/tests/__init__.py


+ 2 - 3
netbox/users/tests/test_models.py

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