registry: fix Regexp initialization when the default value is not None.

This commit is contained in:
Valentin Lorentz 2020-09-15 09:57:15 +02:00
parent 864315cc5f
commit ac94c5291e
2 changed files with 31 additions and 10 deletions

View File

@ -751,24 +751,35 @@ class Regexp(Value):
"""Value must be a valid regular expression.""" """Value must be a valid regular expression."""
errormsg = _('Value must be a valid regular expression, not %r.') 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): def error(self, e):
s = 'Value must be a regexp of the form m/.../ or /.../. %s' % e s = 'Value must be a regexp of the form m/.../ or /.../. %s' % e
e = InvalidRegistryValue(s) e = InvalidRegistryValue(s)
e.value = self e.value = self
raise e 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): def set(self, s):
try: try:
if s: v = self._convertFromString(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
except ValueError as e: except ValueError as e:
self.error(e) self.error(e)
else: else:

View File

@ -183,6 +183,16 @@ class ValuesTestCase(SupyTestCase):
v.set('') v.set('')
self.assertEqual(v(), None) 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): def testBackslashesKeys(self):
conf.supybot.reply.whenAddressedBy.strings.get(':foo').set('=/*') conf.supybot.reply.whenAddressedBy.strings.get(':foo').set('=/*')
filename = conf.supybot.directories.conf.dirize('backslashes1.conf') filename = conf.supybot.directories.conf.dirize('backslashes1.conf')