From ac94c5291e440b1bbc3b6d96a9ebf35536832d73 Mon Sep 17 00:00:00 2001 From: Valentin Lorentz Date: Tue, 15 Sep 2020 09:57:15 +0200 Subject: [PATCH] registry: fix Regexp initialization when the default value is not None. --- src/registry.py | 31 +++++++++++++++++++++---------- test/test_registry.py | 10 ++++++++++ 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/src/registry.py b/src/registry.py index 0cfd00cca..ed1c77c0c 100644 --- a/src/registry.py +++ b/src/registry.py @@ -751,24 +751,35 @@ class Regexp(Value): """Value must be a valid regular expression.""" errormsg = _('Value must be a valid regular expression, not %r.') + def __init__(self, default, *args, **kwargs): + # We're not supposed to do convertions here, BUT this is needed + # when the value is set programmatically because the value + # plugins set (a string) is not the same as the one they get + # (a compiled pattern object) + default = self._convertFromString(default) + super().__init__(default, *args, **kwargs) + def error(self, e): s = 'Value must be a regexp of the form m/.../ or /.../. %s' % e e = InvalidRegistryValue(s) e.value = self raise e + def _convertFromString(self, s): + if s: + # We need to preserve the original string, as it's shown in + # the user interface and the config file. + # It might be tempting to set the original string as an + # attribute, but doing so would result in inconsistent states + # for childs of this variable, should they be reset, or the + # value of there parent change. + return (s, utils.str.perlReToPythonRe(s)) + else: + return None + def set(self, s): try: - if s: - # We need to preserve the original string, as it's shown in - # the user interface and the config file. - # It might be tempting to set the original string as an - # attribute, but doing so would result in inconsistent states - # for childs of this variable, should they be reset, or the - # value of there parent change. - v = (s, utils.str.perlReToPythonRe(s)) - else: - v = None + v = self._convertFromString(s) except ValueError as e: self.error(e) else: diff --git a/test/test_registry.py b/test/test_registry.py index 826db4fd4..956f3bfbd 100644 --- a/test/test_registry.py +++ b/test/test_registry.py @@ -183,6 +183,16 @@ class ValuesTestCase(SupyTestCase): v.set('') self.assertEqual(v(), None) + def testRegexpDefaultString(self): + v = registry.Regexp('m/foo/', 'help') + self.assertEqual(v(), re.compile('foo')) + + v = registry.Regexp('', 'help') + self.assertEqual(v(), None) + + v = registry.Regexp(None, 'help') + self.assertEqual(v(), None) + def testBackslashesKeys(self): conf.supybot.reply.whenAddressedBy.strings.get(':foo').set('=/*') filename = conf.supybot.directories.conf.dirize('backslashes1.conf')