Regular expressions for things like that probably need tests:
import unittest
import re
# Verbose regular expression! http://docs.python.org/library/re.html#re.X
p = r"""
(?P<name>[^(]+) # Match the pre-open-paren name.
\( # Open paren
(?P<fields> # Comma-separated fields
(?:
[a-zA-Z0-9_-]+
(?:,\ ) # Subsequent fields must separated by space and comma
)*
[a-zA-Z0-9_-]+ # At least one field. No trailing comma or space allowed.
)
\) # Close-paren
"""
# Compiled for speed!
cp = re.compile(p, re.VERBOSE)
class Foo(object):
pass
def validateAndBuild(s):
"""Validate a string and return a built object.
"""
match = cp.search(s)
if match is None:
raise ValueError('Bad schema: %s' % s)
schema = match.groupdict()
foo = Foo()
foo.name = schema['name']
foo.fields = schema['fields'].split(', ')
return foo
class ValidationTest(unittest.TestCase):
def testValidString(self):
s = "schema(field1, field2, field3, field4, fieldn)"
obj = validateAndBuild(s)
self.assertEqual(obj.name, 'schema')
self.assertEqual(obj.fields, ['field1', 'field2', 'field3', 'field4', 'fieldn'])
invalid = [
'schema field1 field2',
'schema(field1',
'schema(field1 field2)',
]
def testInvalidString(self):
for s in self.invalid:
self.assertRaises(ValueError, validateAndBuild, s)
if __name__ == '__main__':
unittest.main()