validate.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  1. # validate.py
  2. # A Validator object
  3. # Copyright (C) 2005-2010 Michael Foord, Mark Andrews, Nicola Larosa
  4. # E-mail: fuzzyman AT voidspace DOT org DOT uk
  5. # mark AT la-la DOT com
  6. # nico AT tekNico DOT net
  7. # This software is licensed under the terms of the BSD license.
  8. # http://www.voidspace.org.uk/python/license.shtml
  9. # Basically you're free to copy, modify, distribute and relicense it,
  10. # So long as you keep a copy of the license with it.
  11. # Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
  12. # For information about bugfixes, updates and support, please join the
  13. # ConfigObj mailing list:
  14. # http://lists.sourceforge.net/lists/listinfo/configobj-develop
  15. # Comments, suggestions and bug reports welcome.
  16. """
  17. The Validator object is used to check that supplied values
  18. conform to a specification.
  19. The value can be supplied as a string - e.g. from a config file.
  20. In this case the check will also *convert* the value to
  21. the required type. This allows you to add validation
  22. as a transparent layer to access data stored as strings.
  23. The validation checks that the data is correct *and*
  24. converts it to the expected type.
  25. Some standard checks are provided for basic data types.
  26. Additional checks are easy to write. They can be
  27. provided when the ``Validator`` is instantiated or
  28. added afterwards.
  29. The standard functions work with the following basic data types :
  30. * integers
  31. * floats
  32. * booleans
  33. * strings
  34. * ip_addr
  35. plus lists of these datatypes
  36. Adding additional checks is done through coding simple functions.
  37. The full set of standard checks are :
  38. * 'integer': matches integer values (including negative)
  39. Takes optional 'min' and 'max' arguments : ::
  40. integer()
  41. integer(3, 9) # any value from 3 to 9
  42. integer(min=0) # any positive value
  43. integer(max=9)
  44. * 'float': matches float values
  45. Has the same parameters as the integer check.
  46. * 'boolean': matches boolean values - ``True`` or ``False``
  47. Acceptable string values for True are :
  48. true, on, yes, 1
  49. Acceptable string values for False are :
  50. false, off, no, 0
  51. Any other value raises an error.
  52. * 'ip_addr': matches an Internet Protocol address, v.4, represented
  53. by a dotted-quad string, i.e. '1.2.3.4'.
  54. * 'string': matches any string.
  55. Takes optional keyword args 'min' and 'max'
  56. to specify min and max lengths of the string.
  57. * 'list': matches any list.
  58. Takes optional keyword args 'min', and 'max' to specify min and
  59. max sizes of the list. (Always returns a list.)
  60. * 'tuple': matches any tuple.
  61. Takes optional keyword args 'min', and 'max' to specify min and
  62. max sizes of the tuple. (Always returns a tuple.)
  63. * 'int_list': Matches a list of integers.
  64. Takes the same arguments as list.
  65. * 'float_list': Matches a list of floats.
  66. Takes the same arguments as list.
  67. * 'bool_list': Matches a list of boolean values.
  68. Takes the same arguments as list.
  69. * 'ip_addr_list': Matches a list of IP addresses.
  70. Takes the same arguments as list.
  71. * 'string_list': Matches a list of strings.
  72. Takes the same arguments as list.
  73. * 'mixed_list': Matches a list with different types in
  74. specific positions. List size must match
  75. the number of arguments.
  76. Each position can be one of :
  77. 'integer', 'float', 'ip_addr', 'string', 'boolean'
  78. So to specify a list with two strings followed
  79. by two integers, you write the check as : ::
  80. mixed_list('string', 'string', 'integer', 'integer')
  81. * 'pass': This check matches everything ! It never fails
  82. and the value is unchanged.
  83. It is also the default if no check is specified.
  84. * 'option': This check matches any from a list of options.
  85. You specify this check with : ::
  86. option('option 1', 'option 2', 'option 3')
  87. You can supply a default value (returned if no value is supplied)
  88. using the default keyword argument.
  89. You specify a list argument for default using a list constructor syntax in
  90. the check : ::
  91. checkname(arg1, arg2, default=list('val 1', 'val 2', 'val 3'))
  92. A badly formatted set of arguments will raise a ``VdtParamError``.
  93. """
  94. __version__ = '1.0.1'
  95. __all__ = (
  96. '__version__',
  97. 'dottedQuadToNum',
  98. 'numToDottedQuad',
  99. 'ValidateError',
  100. 'VdtUnknownCheckError',
  101. 'VdtParamError',
  102. 'VdtTypeError',
  103. 'VdtValueError',
  104. 'VdtValueTooSmallError',
  105. 'VdtValueTooBigError',
  106. 'VdtValueTooShortError',
  107. 'VdtValueTooLongError',
  108. 'VdtMissingValue',
  109. 'Validator',
  110. 'is_integer',
  111. 'is_float',
  112. 'is_boolean',
  113. 'is_list',
  114. 'is_tuple',
  115. 'is_ip_addr',
  116. 'is_string',
  117. 'is_int_list',
  118. 'is_bool_list',
  119. 'is_float_list',
  120. 'is_string_list',
  121. 'is_ip_addr_list',
  122. 'is_mixed_list',
  123. 'is_option',
  124. '__docformat__',
  125. )
  126. import re
  127. _list_arg = re.compile(r'''
  128. (?:
  129. ([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*list\(
  130. (
  131. (?:
  132. \s*
  133. (?:
  134. (?:".*?")| # double quotes
  135. (?:'.*?')| # single quotes
  136. (?:[^'",\s\)][^,\)]*?) # unquoted
  137. )
  138. \s*,\s*
  139. )*
  140. (?:
  141. (?:".*?")| # double quotes
  142. (?:'.*?')| # single quotes
  143. (?:[^'",\s\)][^,\)]*?) # unquoted
  144. )? # last one
  145. )
  146. \)
  147. )
  148. ''', re.VERBOSE | re.DOTALL) # two groups
  149. _list_members = re.compile(r'''
  150. (
  151. (?:".*?")| # double quotes
  152. (?:'.*?')| # single quotes
  153. (?:[^'",\s=][^,=]*?) # unquoted
  154. )
  155. (?:
  156. (?:\s*,\s*)|(?:\s*$) # comma
  157. )
  158. ''', re.VERBOSE | re.DOTALL) # one group
  159. _paramstring = r'''
  160. (?:
  161. (
  162. (?:
  163. [a-zA-Z_][a-zA-Z0-9_]*\s*=\s*list\(
  164. (?:
  165. \s*
  166. (?:
  167. (?:".*?")| # double quotes
  168. (?:'.*?')| # single quotes
  169. (?:[^'",\s\)][^,\)]*?) # unquoted
  170. )
  171. \s*,\s*
  172. )*
  173. (?:
  174. (?:".*?")| # double quotes
  175. (?:'.*?')| # single quotes
  176. (?:[^'",\s\)][^,\)]*?) # unquoted
  177. )? # last one
  178. \)
  179. )|
  180. (?:
  181. (?:".*?")| # double quotes
  182. (?:'.*?')| # single quotes
  183. (?:[^'",\s=][^,=]*?)| # unquoted
  184. (?: # keyword argument
  185. [a-zA-Z_][a-zA-Z0-9_]*\s*=\s*
  186. (?:
  187. (?:".*?")| # double quotes
  188. (?:'.*?')| # single quotes
  189. (?:[^'",\s=][^,=]*?) # unquoted
  190. )
  191. )
  192. )
  193. )
  194. (?:
  195. (?:\s*,\s*)|(?:\s*$) # comma
  196. )
  197. )
  198. '''
  199. _matchstring = '^%s*' % _paramstring
  200. # Python pre 2.2.1 doesn't have bool
  201. try:
  202. bool
  203. except NameError:
  204. def bool(val):
  205. """Simple boolean equivalent function. """
  206. if val:
  207. return 1
  208. else:
  209. return 0
  210. def dottedQuadToNum(ip):
  211. """
  212. Convert decimal dotted quad string to long integer
  213. >>> int(dottedQuadToNum('1 '))
  214. 1
  215. >>> int(dottedQuadToNum(' 1.2'))
  216. 16777218
  217. >>> int(dottedQuadToNum(' 1.2.3 '))
  218. 16908291
  219. >>> int(dottedQuadToNum('1.2.3.4'))
  220. 16909060
  221. >>> dottedQuadToNum('255.255.255.255')
  222. 4294967295L
  223. >>> dottedQuadToNum('255.255.255.256')
  224. Traceback (most recent call last):
  225. ValueError: Not a good dotted-quad IP: 255.255.255.256
  226. """
  227. # import here to avoid it when ip_addr values are not used
  228. import socket, struct
  229. try:
  230. return struct.unpack('!L',
  231. socket.inet_aton(ip.strip()))[0]
  232. except socket.error:
  233. # bug in inet_aton, corrected in Python 2.4
  234. if ip.strip() == '255.255.255.255':
  235. return 0xFFFFFFFFL
  236. else:
  237. raise ValueError('Not a good dotted-quad IP: %s' % ip)
  238. return
  239. def numToDottedQuad(num):
  240. """
  241. Convert long int to dotted quad string
  242. >>> numToDottedQuad(-1L)
  243. Traceback (most recent call last):
  244. ValueError: Not a good numeric IP: -1
  245. >>> numToDottedQuad(1L)
  246. '0.0.0.1'
  247. >>> numToDottedQuad(16777218L)
  248. '1.0.0.2'
  249. >>> numToDottedQuad(16908291L)
  250. '1.2.0.3'
  251. >>> numToDottedQuad(16909060L)
  252. '1.2.3.4'
  253. >>> numToDottedQuad(4294967295L)
  254. '255.255.255.255'
  255. >>> numToDottedQuad(4294967296L)
  256. Traceback (most recent call last):
  257. ValueError: Not a good numeric IP: 4294967296
  258. """
  259. # import here to avoid it when ip_addr values are not used
  260. import socket, struct
  261. # no need to intercept here, 4294967295L is fine
  262. if num > 4294967295L or num < 0:
  263. raise ValueError('Not a good numeric IP: %s' % num)
  264. try:
  265. return socket.inet_ntoa(
  266. struct.pack('!L', long(num)))
  267. except (socket.error, struct.error, OverflowError):
  268. raise ValueError('Not a good numeric IP: %s' % num)
  269. class ValidateError(Exception):
  270. """
  271. This error indicates that the check failed.
  272. It can be the base class for more specific errors.
  273. Any check function that fails ought to raise this error.
  274. (or a subclass)
  275. >>> raise ValidateError
  276. Traceback (most recent call last):
  277. ValidateError
  278. """
  279. class VdtMissingValue(ValidateError):
  280. """No value was supplied to a check that needed one."""
  281. class VdtUnknownCheckError(ValidateError):
  282. """An unknown check function was requested"""
  283. def __init__(self, value):
  284. """
  285. >>> raise VdtUnknownCheckError('yoda')
  286. Traceback (most recent call last):
  287. VdtUnknownCheckError: the check "yoda" is unknown.
  288. """
  289. ValidateError.__init__(self, 'the check "%s" is unknown.' % (value,))
  290. class VdtParamError(SyntaxError):
  291. """An incorrect parameter was passed"""
  292. def __init__(self, name, value):
  293. """
  294. >>> raise VdtParamError('yoda', 'jedi')
  295. Traceback (most recent call last):
  296. VdtParamError: passed an incorrect value "jedi" for parameter "yoda".
  297. """
  298. SyntaxError.__init__(self, 'passed an incorrect value "%s" for parameter "%s".' % (value, name))
  299. class VdtTypeError(ValidateError):
  300. """The value supplied was of the wrong type"""
  301. def __init__(self, value):
  302. """
  303. >>> raise VdtTypeError('jedi')
  304. Traceback (most recent call last):
  305. VdtTypeError: the value "jedi" is of the wrong type.
  306. """
  307. ValidateError.__init__(self, 'the value "%s" is of the wrong type.' % (value,))
  308. class VdtValueError(ValidateError):
  309. """The value supplied was of the correct type, but was not an allowed value."""
  310. def __init__(self, value):
  311. """
  312. >>> raise VdtValueError('jedi')
  313. Traceback (most recent call last):
  314. VdtValueError: the value "jedi" is unacceptable.
  315. """
  316. ValidateError.__init__(self, 'the value "%s" is unacceptable.' % (value,))
  317. class VdtValueTooSmallError(VdtValueError):
  318. """The value supplied was of the correct type, but was too small."""
  319. def __init__(self, value):
  320. """
  321. >>> raise VdtValueTooSmallError('0')
  322. Traceback (most recent call last):
  323. VdtValueTooSmallError: the value "0" is too small.
  324. """
  325. ValidateError.__init__(self, 'the value "%s" is too small.' % (value,))
  326. class VdtValueTooBigError(VdtValueError):
  327. """The value supplied was of the correct type, but was too big."""
  328. def __init__(self, value):
  329. """
  330. >>> raise VdtValueTooBigError('1')
  331. Traceback (most recent call last):
  332. VdtValueTooBigError: the value "1" is too big.
  333. """
  334. ValidateError.__init__(self, 'the value "%s" is too big.' % (value,))
  335. class VdtValueTooShortError(VdtValueError):
  336. """The value supplied was of the correct type, but was too short."""
  337. def __init__(self, value):
  338. """
  339. >>> raise VdtValueTooShortError('jed')
  340. Traceback (most recent call last):
  341. VdtValueTooShortError: the value "jed" is too short.
  342. """
  343. ValidateError.__init__(
  344. self,
  345. 'the value "%s" is too short.' % (value,))
  346. class VdtValueTooLongError(VdtValueError):
  347. """The value supplied was of the correct type, but was too long."""
  348. def __init__(self, value):
  349. """
  350. >>> raise VdtValueTooLongError('jedie')
  351. Traceback (most recent call last):
  352. VdtValueTooLongError: the value "jedie" is too long.
  353. """
  354. ValidateError.__init__(self, 'the value "%s" is too long.' % (value,))
  355. class Validator(object):
  356. """
  357. Validator is an object that allows you to register a set of 'checks'.
  358. These checks take input and test that it conforms to the check.
  359. This can also involve converting the value from a string into
  360. the correct datatype.
  361. The ``check`` method takes an input string which configures which
  362. check is to be used and applies that check to a supplied value.
  363. An example input string would be:
  364. 'int_range(param1, param2)'
  365. You would then provide something like:
  366. >>> def int_range_check(value, min, max):
  367. ... # turn min and max from strings to integers
  368. ... min = int(min)
  369. ... max = int(max)
  370. ... # check that value is of the correct type.
  371. ... # possible valid inputs are integers or strings
  372. ... # that represent integers
  373. ... if not isinstance(value, (int, long, basestring)):
  374. ... raise VdtTypeError(value)
  375. ... elif isinstance(value, basestring):
  376. ... # if we are given a string
  377. ... # attempt to convert to an integer
  378. ... try:
  379. ... value = int(value)
  380. ... except ValueError:
  381. ... raise VdtValueError(value)
  382. ... # check the value is between our constraints
  383. ... if not min <= value:
  384. ... raise VdtValueTooSmallError(value)
  385. ... if not value <= max:
  386. ... raise VdtValueTooBigError(value)
  387. ... return value
  388. >>> fdict = {'int_range': int_range_check}
  389. >>> vtr1 = Validator(fdict)
  390. >>> vtr1.check('int_range(20, 40)', '30')
  391. 30
  392. >>> vtr1.check('int_range(20, 40)', '60')
  393. Traceback (most recent call last):
  394. VdtValueTooBigError: the value "60" is too big.
  395. New functions can be added with : ::
  396. >>> vtr2 = Validator()
  397. >>> vtr2.functions['int_range'] = int_range_check
  398. Or by passing in a dictionary of functions when Validator
  399. is instantiated.
  400. Your functions *can* use keyword arguments,
  401. but the first argument should always be 'value'.
  402. If the function doesn't take additional arguments,
  403. the parentheses are optional in the check.
  404. It can be written with either of : ::
  405. keyword = function_name
  406. keyword = function_name()
  407. The first program to utilise Validator() was Michael Foord's
  408. ConfigObj, an alternative to ConfigParser which supports lists and
  409. can validate a config file using a config schema.
  410. For more details on using Validator with ConfigObj see:
  411. http://www.voidspace.org.uk/python/configobj.html
  412. """
  413. # this regex does the initial parsing of the checks
  414. _func_re = re.compile(r'(.+?)\((.*)\)', re.DOTALL)
  415. # this regex takes apart keyword arguments
  416. _key_arg = re.compile(r'^([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(.*)$', re.DOTALL)
  417. # this regex finds keyword=list(....) type values
  418. _list_arg = _list_arg
  419. # this regex takes individual values out of lists - in one pass
  420. _list_members = _list_members
  421. # These regexes check a set of arguments for validity
  422. # and then pull the members out
  423. _paramfinder = re.compile(_paramstring, re.VERBOSE | re.DOTALL)
  424. _matchfinder = re.compile(_matchstring, re.VERBOSE | re.DOTALL)
  425. def __init__(self, functions=None):
  426. """
  427. >>> vtri = Validator()
  428. """
  429. self.functions = {
  430. '': self._pass,
  431. 'integer': is_integer,
  432. 'float': is_float,
  433. 'boolean': is_boolean,
  434. 'ip_addr': is_ip_addr,
  435. 'string': is_string,
  436. 'list': is_list,
  437. 'tuple': is_tuple,
  438. 'int_list': is_int_list,
  439. 'float_list': is_float_list,
  440. 'bool_list': is_bool_list,
  441. 'ip_addr_list': is_ip_addr_list,
  442. 'string_list': is_string_list,
  443. 'mixed_list': is_mixed_list,
  444. 'pass': self._pass,
  445. 'option': is_option,
  446. 'force_list': force_list,
  447. }
  448. if functions is not None:
  449. self.functions.update(functions)
  450. # tekNico: for use by ConfigObj
  451. self.baseErrorClass = ValidateError
  452. self._cache = {}
  453. def check(self, check, value, missing=False):
  454. """
  455. Usage: check(check, value)
  456. Arguments:
  457. check: string representing check to apply (including arguments)
  458. value: object to be checked
  459. Returns value, converted to correct type if necessary
  460. If the check fails, raises a ``ValidateError`` subclass.
  461. >>> vtor.check('yoda', '')
  462. Traceback (most recent call last):
  463. VdtUnknownCheckError: the check "yoda" is unknown.
  464. >>> vtor.check('yoda()', '')
  465. Traceback (most recent call last):
  466. VdtUnknownCheckError: the check "yoda" is unknown.
  467. >>> vtor.check('string(default="")', '', missing=True)
  468. ''
  469. """
  470. fun_name, fun_args, fun_kwargs, default = self._parse_with_caching(check)
  471. if missing:
  472. if default is None:
  473. # no information needed here - to be handled by caller
  474. raise VdtMissingValue()
  475. value = self._handle_none(default)
  476. if value is None:
  477. return None
  478. return self._check_value(value, fun_name, fun_args, fun_kwargs)
  479. def _handle_none(self, value):
  480. if value == 'None':
  481. return None
  482. elif value in ("'None'", '"None"'):
  483. # Special case a quoted None
  484. value = self._unquote(value)
  485. return value
  486. def _parse_with_caching(self, check):
  487. if check in self._cache:
  488. fun_name, fun_args, fun_kwargs, default = self._cache[check]
  489. # We call list and dict below to work with *copies* of the data
  490. # rather than the original (which are mutable of course)
  491. fun_args = list(fun_args)
  492. fun_kwargs = dict(fun_kwargs)
  493. else:
  494. fun_name, fun_args, fun_kwargs, default = self._parse_check(check)
  495. fun_kwargs = dict([(str(key), value) for (key, value) in fun_kwargs.items()])
  496. self._cache[check] = fun_name, list(fun_args), dict(fun_kwargs), default
  497. return fun_name, fun_args, fun_kwargs, default
  498. def _check_value(self, value, fun_name, fun_args, fun_kwargs):
  499. try:
  500. fun = self.functions[fun_name]
  501. except KeyError:
  502. raise VdtUnknownCheckError(fun_name)
  503. else:
  504. return fun(value, *fun_args, **fun_kwargs)
  505. def _parse_check(self, check):
  506. fun_match = self._func_re.match(check)
  507. if fun_match:
  508. fun_name = fun_match.group(1)
  509. arg_string = fun_match.group(2)
  510. arg_match = self._matchfinder.match(arg_string)
  511. if arg_match is None:
  512. # Bad syntax
  513. raise VdtParamError('Bad syntax in check "%s".' % check)
  514. fun_args = []
  515. fun_kwargs = {}
  516. # pull out args of group 2
  517. for arg in self._paramfinder.findall(arg_string):
  518. # args may need whitespace removing (before removing quotes)
  519. arg = arg.strip()
  520. listmatch = self._list_arg.match(arg)
  521. if listmatch:
  522. key, val = self._list_handle(listmatch)
  523. fun_kwargs[key] = val
  524. continue
  525. keymatch = self._key_arg.match(arg)
  526. if keymatch:
  527. val = keymatch.group(2)
  528. if not val in ("'None'", '"None"'):
  529. # Special case a quoted None
  530. val = self._unquote(val)
  531. fun_kwargs[keymatch.group(1)] = val
  532. continue
  533. fun_args.append(self._unquote(arg))
  534. else:
  535. # allows for function names without (args)
  536. return check, (), {}, None
  537. # Default must be deleted if the value is specified too,
  538. # otherwise the check function will get a spurious "default" keyword arg
  539. default = fun_kwargs.pop('default', None)
  540. return fun_name, fun_args, fun_kwargs, default
  541. def _unquote(self, val):
  542. """Unquote a value if necessary."""
  543. if (len(val) >= 2) and (val[0] in ("'", '"')) and (val[0] == val[-1]):
  544. val = val[1:-1]
  545. return val
  546. def _list_handle(self, listmatch):
  547. """Take apart a ``keyword=list('val, 'val')`` type string."""
  548. out = []
  549. name = listmatch.group(1)
  550. args = listmatch.group(2)
  551. for arg in self._list_members.findall(args):
  552. out.append(self._unquote(arg))
  553. return name, out
  554. def _pass(self, value):
  555. """
  556. Dummy check that always passes
  557. >>> vtor.check('', 0)
  558. 0
  559. >>> vtor.check('', '0')
  560. '0'
  561. """
  562. return value
  563. def get_default_value(self, check):
  564. """
  565. Given a check, return the default value for the check
  566. (converted to the right type).
  567. If the check doesn't specify a default value then a
  568. ``KeyError`` will be raised.
  569. """
  570. fun_name, fun_args, fun_kwargs, default = self._parse_with_caching(check)
  571. if default is None:
  572. raise KeyError('Check "%s" has no default value.' % check)
  573. value = self._handle_none(default)
  574. if value is None:
  575. return value
  576. return self._check_value(value, fun_name, fun_args, fun_kwargs)
  577. def _is_num_param(names, values, to_float=False):
  578. """
  579. Return numbers from inputs or raise VdtParamError.
  580. Lets ``None`` pass through.
  581. Pass in keyword argument ``to_float=True`` to
  582. use float for the conversion rather than int.
  583. >>> _is_num_param(('', ''), (0, 1.0))
  584. [0, 1]
  585. >>> _is_num_param(('', ''), (0, 1.0), to_float=True)
  586. [0.0, 1.0]
  587. >>> _is_num_param(('a'), ('a'))
  588. Traceback (most recent call last):
  589. VdtParamError: passed an incorrect value "a" for parameter "a".
  590. """
  591. fun = to_float and float or int
  592. out_params = []
  593. for (name, val) in zip(names, values):
  594. if val is None:
  595. out_params.append(val)
  596. elif isinstance(val, (int, long, float, basestring)):
  597. try:
  598. out_params.append(fun(val))
  599. except ValueError, e:
  600. raise VdtParamError(name, val)
  601. else:
  602. raise VdtParamError(name, val)
  603. return out_params
  604. # built in checks
  605. # you can override these by setting the appropriate name
  606. # in Validator.functions
  607. # note: if the params are specified wrongly in your input string,
  608. # you will also raise errors.
  609. def is_integer(value, min=None, max=None):
  610. """
  611. A check that tests that a given value is an integer (int, or long)
  612. and optionally, between bounds. A negative value is accepted, while
  613. a float will fail.
  614. If the value is a string, then the conversion is done - if possible.
  615. Otherwise a VdtError is raised.
  616. >>> vtor.check('integer', '-1')
  617. -1
  618. >>> vtor.check('integer', '0')
  619. 0
  620. >>> vtor.check('integer', 9)
  621. 9
  622. >>> vtor.check('integer', 'a')
  623. Traceback (most recent call last):
  624. VdtTypeError: the value "a" is of the wrong type.
  625. >>> vtor.check('integer', '2.2')
  626. Traceback (most recent call last):
  627. VdtTypeError: the value "2.2" is of the wrong type.
  628. >>> vtor.check('integer(10)', '20')
  629. 20
  630. >>> vtor.check('integer(max=20)', '15')
  631. 15
  632. >>> vtor.check('integer(10)', '9')
  633. Traceback (most recent call last):
  634. VdtValueTooSmallError: the value "9" is too small.
  635. >>> vtor.check('integer(10)', 9)
  636. Traceback (most recent call last):
  637. VdtValueTooSmallError: the value "9" is too small.
  638. >>> vtor.check('integer(max=20)', '35')
  639. Traceback (most recent call last):
  640. VdtValueTooBigError: the value "35" is too big.
  641. >>> vtor.check('integer(max=20)', 35)
  642. Traceback (most recent call last):
  643. VdtValueTooBigError: the value "35" is too big.
  644. >>> vtor.check('integer(0, 9)', False)
  645. 0
  646. """
  647. (min_val, max_val) = _is_num_param(('min', 'max'), (min, max))
  648. if not isinstance(value, (int, long, basestring)):
  649. raise VdtTypeError(value)
  650. if isinstance(value, basestring):
  651. # if it's a string - does it represent an integer ?
  652. try:
  653. value = int(value)
  654. except ValueError:
  655. raise VdtTypeError(value)
  656. if (min_val is not None) and (value < min_val):
  657. raise VdtValueTooSmallError(value)
  658. if (max_val is not None) and (value > max_val):
  659. raise VdtValueTooBigError(value)
  660. return value
  661. def is_float(value, min=None, max=None):
  662. """
  663. A check that tests that a given value is a float
  664. (an integer will be accepted), and optionally - that it is between bounds.
  665. If the value is a string, then the conversion is done - if possible.
  666. Otherwise a VdtError is raised.
  667. This can accept negative values.
  668. >>> vtor.check('float', '2')
  669. 2.0
  670. From now on we multiply the value to avoid comparing decimals
  671. >>> vtor.check('float', '-6.8') * 10
  672. -68.0
  673. >>> vtor.check('float', '12.2') * 10
  674. 122.0
  675. >>> vtor.check('float', 8.4) * 10
  676. 84.0
  677. >>> vtor.check('float', 'a')
  678. Traceback (most recent call last):
  679. VdtTypeError: the value "a" is of the wrong type.
  680. >>> vtor.check('float(10.1)', '10.2') * 10
  681. 102.0
  682. >>> vtor.check('float(max=20.2)', '15.1') * 10
  683. 151.0
  684. >>> vtor.check('float(10.0)', '9.0')
  685. Traceback (most recent call last):
  686. VdtValueTooSmallError: the value "9.0" is too small.
  687. >>> vtor.check('float(max=20.0)', '35.0')
  688. Traceback (most recent call last):
  689. VdtValueTooBigError: the value "35.0" is too big.
  690. """
  691. (min_val, max_val) = _is_num_param(
  692. ('min', 'max'), (min, max), to_float=True)
  693. if not isinstance(value, (int, long, float, basestring)):
  694. raise VdtTypeError(value)
  695. if not isinstance(value, float):
  696. # if it's a string - does it represent a float ?
  697. try:
  698. value = float(value)
  699. except ValueError:
  700. raise VdtTypeError(value)
  701. if (min_val is not None) and (value < min_val):
  702. raise VdtValueTooSmallError(value)
  703. if (max_val is not None) and (value > max_val):
  704. raise VdtValueTooBigError(value)
  705. return value
  706. bool_dict = {
  707. True: True, 'on': True, '1': True, 'true': True, 'yes': True,
  708. False: False, 'off': False, '0': False, 'false': False, 'no': False,
  709. }
  710. def is_boolean(value):
  711. """
  712. Check if the value represents a boolean.
  713. >>> vtor.check('boolean', 0)
  714. 0
  715. >>> vtor.check('boolean', False)
  716. 0
  717. >>> vtor.check('boolean', '0')
  718. 0
  719. >>> vtor.check('boolean', 'off')
  720. 0
  721. >>> vtor.check('boolean', 'false')
  722. 0
  723. >>> vtor.check('boolean', 'no')
  724. 0
  725. >>> vtor.check('boolean', 'nO')
  726. 0
  727. >>> vtor.check('boolean', 'NO')
  728. 0
  729. >>> vtor.check('boolean', 1)
  730. 1
  731. >>> vtor.check('boolean', True)
  732. 1
  733. >>> vtor.check('boolean', '1')
  734. 1
  735. >>> vtor.check('boolean', 'on')
  736. 1
  737. >>> vtor.check('boolean', 'true')
  738. 1
  739. >>> vtor.check('boolean', 'yes')
  740. 1
  741. >>> vtor.check('boolean', 'Yes')
  742. 1
  743. >>> vtor.check('boolean', 'YES')
  744. 1
  745. >>> vtor.check('boolean', '')
  746. Traceback (most recent call last):
  747. VdtTypeError: the value "" is of the wrong type.
  748. >>> vtor.check('boolean', 'up')
  749. Traceback (most recent call last):
  750. VdtTypeError: the value "up" is of the wrong type.
  751. """
  752. if isinstance(value, basestring):
  753. try:
  754. return bool_dict[value.lower()]
  755. except KeyError:
  756. raise VdtTypeError(value)
  757. # we do an equality test rather than an identity test
  758. # this ensures Python 2.2 compatibilty
  759. # and allows 0 and 1 to represent True and False
  760. if value == False:
  761. return False
  762. elif value == True:
  763. return True
  764. else:
  765. raise VdtTypeError(value)
  766. def is_ip_addr(value):
  767. """
  768. Check that the supplied value is an Internet Protocol address, v.4,
  769. represented by a dotted-quad string, i.e. '1.2.3.4'.
  770. >>> vtor.check('ip_addr', '1 ')
  771. '1'
  772. >>> vtor.check('ip_addr', ' 1.2')
  773. '1.2'
  774. >>> vtor.check('ip_addr', ' 1.2.3 ')
  775. '1.2.3'
  776. >>> vtor.check('ip_addr', '1.2.3.4')
  777. '1.2.3.4'
  778. >>> vtor.check('ip_addr', '0.0.0.0')
  779. '0.0.0.0'
  780. >>> vtor.check('ip_addr', '255.255.255.255')
  781. '255.255.255.255'
  782. >>> vtor.check('ip_addr', '255.255.255.256')
  783. Traceback (most recent call last):
  784. VdtValueError: the value "255.255.255.256" is unacceptable.
  785. >>> vtor.check('ip_addr', '1.2.3.4.5')
  786. Traceback (most recent call last):
  787. VdtValueError: the value "1.2.3.4.5" is unacceptable.
  788. >>> vtor.check('ip_addr', 0)
  789. Traceback (most recent call last):
  790. VdtTypeError: the value "0" is of the wrong type.
  791. """
  792. if not isinstance(value, basestring):
  793. raise VdtTypeError(value)
  794. value = value.strip()
  795. try:
  796. dottedQuadToNum(value)
  797. except ValueError:
  798. raise VdtValueError(value)
  799. return value
  800. def is_list(value, min=None, max=None):
  801. """
  802. Check that the value is a list of values.
  803. You can optionally specify the minimum and maximum number of members.
  804. It does no check on list members.
  805. >>> vtor.check('list', ())
  806. []
  807. >>> vtor.check('list', [])
  808. []
  809. >>> vtor.check('list', (1, 2))
  810. [1, 2]
  811. >>> vtor.check('list', [1, 2])
  812. [1, 2]
  813. >>> vtor.check('list(3)', (1, 2))
  814. Traceback (most recent call last):
  815. VdtValueTooShortError: the value "(1, 2)" is too short.
  816. >>> vtor.check('list(max=5)', (1, 2, 3, 4, 5, 6))
  817. Traceback (most recent call last):
  818. VdtValueTooLongError: the value "(1, 2, 3, 4, 5, 6)" is too long.
  819. >>> vtor.check('list(min=3, max=5)', (1, 2, 3, 4))
  820. [1, 2, 3, 4]
  821. >>> vtor.check('list', 0)
  822. Traceback (most recent call last):
  823. VdtTypeError: the value "0" is of the wrong type.
  824. >>> vtor.check('list', '12')
  825. Traceback (most recent call last):
  826. VdtTypeError: the value "12" is of the wrong type.
  827. """
  828. (min_len, max_len) = _is_num_param(('min', 'max'), (min, max))
  829. if isinstance(value, basestring):
  830. raise VdtTypeError(value)
  831. try:
  832. num_members = len(value)
  833. except TypeError:
  834. raise VdtTypeError(value)
  835. if min_len is not None and num_members < min_len:
  836. raise VdtValueTooShortError(value)
  837. if max_len is not None and num_members > max_len:
  838. raise VdtValueTooLongError(value)
  839. return list(value)
  840. def is_tuple(value, min=None, max=None):
  841. """
  842. Check that the value is a tuple of values.
  843. You can optionally specify the minimum and maximum number of members.
  844. It does no check on members.
  845. >>> vtor.check('tuple', ())
  846. ()
  847. >>> vtor.check('tuple', [])
  848. ()
  849. >>> vtor.check('tuple', (1, 2))
  850. (1, 2)
  851. >>> vtor.check('tuple', [1, 2])
  852. (1, 2)
  853. >>> vtor.check('tuple(3)', (1, 2))
  854. Traceback (most recent call last):
  855. VdtValueTooShortError: the value "(1, 2)" is too short.
  856. >>> vtor.check('tuple(max=5)', (1, 2, 3, 4, 5, 6))
  857. Traceback (most recent call last):
  858. VdtValueTooLongError: the value "(1, 2, 3, 4, 5, 6)" is too long.
  859. >>> vtor.check('tuple(min=3, max=5)', (1, 2, 3, 4))
  860. (1, 2, 3, 4)
  861. >>> vtor.check('tuple', 0)
  862. Traceback (most recent call last):
  863. VdtTypeError: the value "0" is of the wrong type.
  864. >>> vtor.check('tuple', '12')
  865. Traceback (most recent call last):
  866. VdtTypeError: the value "12" is of the wrong type.
  867. """
  868. return tuple(is_list(value, min, max))
  869. def is_string(value, min=None, max=None):
  870. """
  871. Check that the supplied value is a string.
  872. You can optionally specify the minimum and maximum number of members.
  873. >>> vtor.check('string', '0')
  874. '0'
  875. >>> vtor.check('string', 0)
  876. Traceback (most recent call last):
  877. VdtTypeError: the value "0" is of the wrong type.
  878. >>> vtor.check('string(2)', '12')
  879. '12'
  880. >>> vtor.check('string(2)', '1')
  881. Traceback (most recent call last):
  882. VdtValueTooShortError: the value "1" is too short.
  883. >>> vtor.check('string(min=2, max=3)', '123')
  884. '123'
  885. >>> vtor.check('string(min=2, max=3)', '1234')
  886. Traceback (most recent call last):
  887. VdtValueTooLongError: the value "1234" is too long.
  888. """
  889. if not isinstance(value, basestring):
  890. raise VdtTypeError(value)
  891. (min_len, max_len) = _is_num_param(('min', 'max'), (min, max))
  892. try:
  893. num_members = len(value)
  894. except TypeError:
  895. raise VdtTypeError(value)
  896. if min_len is not None and num_members < min_len:
  897. raise VdtValueTooShortError(value)
  898. if max_len is not None and num_members > max_len:
  899. raise VdtValueTooLongError(value)
  900. return value
  901. def is_int_list(value, min=None, max=None):
  902. """
  903. Check that the value is a list of integers.
  904. You can optionally specify the minimum and maximum number of members.
  905. Each list member is checked that it is an integer.
  906. >>> vtor.check('int_list', ())
  907. []
  908. >>> vtor.check('int_list', [])
  909. []
  910. >>> vtor.check('int_list', (1, 2))
  911. [1, 2]
  912. >>> vtor.check('int_list', [1, 2])
  913. [1, 2]
  914. >>> vtor.check('int_list', [1, 'a'])
  915. Traceback (most recent call last):
  916. VdtTypeError: the value "a" is of the wrong type.
  917. """
  918. return [is_integer(mem) for mem in is_list(value, min, max)]
  919. def is_bool_list(value, min=None, max=None):
  920. """
  921. Check that the value is a list of booleans.
  922. You can optionally specify the minimum and maximum number of members.
  923. Each list member is checked that it is a boolean.
  924. >>> vtor.check('bool_list', ())
  925. []
  926. >>> vtor.check('bool_list', [])
  927. []
  928. >>> check_res = vtor.check('bool_list', (True, False))
  929. >>> check_res == [True, False]
  930. 1
  931. >>> check_res = vtor.check('bool_list', [True, False])
  932. >>> check_res == [True, False]
  933. 1
  934. >>> vtor.check('bool_list', [True, 'a'])
  935. Traceback (most recent call last):
  936. VdtTypeError: the value "a" is of the wrong type.
  937. """
  938. return [is_boolean(mem) for mem in is_list(value, min, max)]
  939. def is_float_list(value, min=None, max=None):
  940. """
  941. Check that the value is a list of floats.
  942. You can optionally specify the minimum and maximum number of members.
  943. Each list member is checked that it is a float.
  944. >>> vtor.check('float_list', ())
  945. []
  946. >>> vtor.check('float_list', [])
  947. []
  948. >>> vtor.check('float_list', (1, 2.0))
  949. [1.0, 2.0]
  950. >>> vtor.check('float_list', [1, 2.0])
  951. [1.0, 2.0]
  952. >>> vtor.check('float_list', [1, 'a'])
  953. Traceback (most recent call last):
  954. VdtTypeError: the value "a" is of the wrong type.
  955. """
  956. return [is_float(mem) for mem in is_list(value, min, max)]
  957. def is_string_list(value, min=None, max=None):
  958. """
  959. Check that the value is a list of strings.
  960. You can optionally specify the minimum and maximum number of members.
  961. Each list member is checked that it is a string.
  962. >>> vtor.check('string_list', ())
  963. []
  964. >>> vtor.check('string_list', [])
  965. []
  966. >>> vtor.check('string_list', ('a', 'b'))
  967. ['a', 'b']
  968. >>> vtor.check('string_list', ['a', 1])
  969. Traceback (most recent call last):
  970. VdtTypeError: the value "1" is of the wrong type.
  971. >>> vtor.check('string_list', 'hello')
  972. Traceback (most recent call last):
  973. VdtTypeError: the value "hello" is of the wrong type.
  974. """
  975. if isinstance(value, basestring):
  976. raise VdtTypeError(value)
  977. return [is_string(mem) for mem in is_list(value, min, max)]
  978. def is_ip_addr_list(value, min=None, max=None):
  979. """
  980. Check that the value is a list of IP addresses.
  981. You can optionally specify the minimum and maximum number of members.
  982. Each list member is checked that it is an IP address.
  983. >>> vtor.check('ip_addr_list', ())
  984. []
  985. >>> vtor.check('ip_addr_list', [])
  986. []
  987. >>> vtor.check('ip_addr_list', ('1.2.3.4', '5.6.7.8'))
  988. ['1.2.3.4', '5.6.7.8']
  989. >>> vtor.check('ip_addr_list', ['a'])
  990. Traceback (most recent call last):
  991. VdtValueError: the value "a" is unacceptable.
  992. """
  993. return [is_ip_addr(mem) for mem in is_list(value, min, max)]
  994. def force_list(value, min=None, max=None):
  995. """
  996. Check that a value is a list, coercing strings into
  997. a list with one member. Useful where users forget the
  998. trailing comma that turns a single value into a list.
  999. You can optionally specify the minimum and maximum number of members.
  1000. A minumum of greater than one will fail if the user only supplies a
  1001. string.
  1002. >>> vtor.check('force_list', ())
  1003. []
  1004. >>> vtor.check('force_list', [])
  1005. []
  1006. >>> vtor.check('force_list', 'hello')
  1007. ['hello']
  1008. """
  1009. if not isinstance(value, (list, tuple)):
  1010. value = [value]
  1011. return is_list(value, min, max)
  1012. fun_dict = {
  1013. 'integer': is_integer,
  1014. 'float': is_float,
  1015. 'ip_addr': is_ip_addr,
  1016. 'string': is_string,
  1017. 'boolean': is_boolean,
  1018. }
  1019. def is_mixed_list(value, *args):
  1020. """
  1021. Check that the value is a list.
  1022. Allow specifying the type of each member.
  1023. Work on lists of specific lengths.
  1024. You specify each member as a positional argument specifying type
  1025. Each type should be one of the following strings :
  1026. 'integer', 'float', 'ip_addr', 'string', 'boolean'
  1027. So you can specify a list of two strings, followed by
  1028. two integers as :
  1029. mixed_list('string', 'string', 'integer', 'integer')
  1030. The length of the list must match the number of positional
  1031. arguments you supply.
  1032. >>> mix_str = "mixed_list('integer', 'float', 'ip_addr', 'string', 'boolean')"
  1033. >>> check_res = vtor.check(mix_str, (1, 2.0, '1.2.3.4', 'a', True))
  1034. >>> check_res == [1, 2.0, '1.2.3.4', 'a', True]
  1035. 1
  1036. >>> check_res = vtor.check(mix_str, ('1', '2.0', '1.2.3.4', 'a', 'True'))
  1037. >>> check_res == [1, 2.0, '1.2.3.4', 'a', True]
  1038. 1
  1039. >>> vtor.check(mix_str, ('b', 2.0, '1.2.3.4', 'a', True))
  1040. Traceback (most recent call last):
  1041. VdtTypeError: the value "b" is of the wrong type.
  1042. >>> vtor.check(mix_str, (1, 2.0, '1.2.3.4', 'a'))
  1043. Traceback (most recent call last):
  1044. VdtValueTooShortError: the value "(1, 2.0, '1.2.3.4', 'a')" is too short.
  1045. >>> vtor.check(mix_str, (1, 2.0, '1.2.3.4', 'a', 1, 'b'))
  1046. Traceback (most recent call last):
  1047. VdtValueTooLongError: the value "(1, 2.0, '1.2.3.4', 'a', 1, 'b')" is too long.
  1048. >>> vtor.check(mix_str, 0)
  1049. Traceback (most recent call last):
  1050. VdtTypeError: the value "0" is of the wrong type.
  1051. This test requires an elaborate setup, because of a change in error string
  1052. output from the interpreter between Python 2.2 and 2.3 .
  1053. >>> res_seq = (
  1054. ... 'passed an incorrect value "',
  1055. ... 'yoda',
  1056. ... '" for parameter "mixed_list".',
  1057. ... )
  1058. >>> res_str = "'".join(res_seq)
  1059. >>> try:
  1060. ... vtor.check('mixed_list("yoda")', ('a'))
  1061. ... except VdtParamError, err:
  1062. ... str(err) == res_str
  1063. 1
  1064. """
  1065. try:
  1066. length = len(value)
  1067. except TypeError:
  1068. raise VdtTypeError(value)
  1069. if length < len(args):
  1070. raise VdtValueTooShortError(value)
  1071. elif length > len(args):
  1072. raise VdtValueTooLongError(value)
  1073. try:
  1074. return [fun_dict[arg](val) for arg, val in zip(args, value)]
  1075. except KeyError, e:
  1076. raise VdtParamError('mixed_list', e)
  1077. def is_option(value, *options):
  1078. """
  1079. This check matches the value to any of a set of options.
  1080. >>> vtor.check('option("yoda", "jedi")', 'yoda')
  1081. 'yoda'
  1082. >>> vtor.check('option("yoda", "jedi")', 'jed')
  1083. Traceback (most recent call last):
  1084. VdtValueError: the value "jed" is unacceptable.
  1085. >>> vtor.check('option("yoda", "jedi")', 0)
  1086. Traceback (most recent call last):
  1087. VdtTypeError: the value "0" is of the wrong type.
  1088. """
  1089. if not isinstance(value, basestring):
  1090. raise VdtTypeError(value)
  1091. if not value in options:
  1092. raise VdtValueError(value)
  1093. return value
  1094. def _test(value, *args, **keywargs):
  1095. """
  1096. A function that exists for test purposes.
  1097. >>> checks = [
  1098. ... '3, 6, min=1, max=3, test=list(a, b, c)',
  1099. ... '3',
  1100. ... '3, 6',
  1101. ... '3,',
  1102. ... 'min=1, test="a b c"',
  1103. ... 'min=5, test="a, b, c"',
  1104. ... 'min=1, max=3, test="a, b, c"',
  1105. ... 'min=-100, test=-99',
  1106. ... 'min=1, max=3',
  1107. ... '3, 6, test="36"',
  1108. ... '3, 6, test="a, b, c"',
  1109. ... '3, max=3, test=list("a", "b", "c")',
  1110. ... '''3, max=3, test=list("'a'", 'b', "x=(c)")''',
  1111. ... "test='x=fish(3)'",
  1112. ... ]
  1113. >>> v = Validator({'test': _test})
  1114. >>> for entry in checks:
  1115. ... print v.check(('test(%s)' % entry), 3)
  1116. (3, ('3', '6'), {'test': ['a', 'b', 'c'], 'max': '3', 'min': '1'})
  1117. (3, ('3',), {})
  1118. (3, ('3', '6'), {})
  1119. (3, ('3',), {})
  1120. (3, (), {'test': 'a b c', 'min': '1'})
  1121. (3, (), {'test': 'a, b, c', 'min': '5'})
  1122. (3, (), {'test': 'a, b, c', 'max': '3', 'min': '1'})
  1123. (3, (), {'test': '-99', 'min': '-100'})
  1124. (3, (), {'max': '3', 'min': '1'})
  1125. (3, ('3', '6'), {'test': '36'})
  1126. (3, ('3', '6'), {'test': 'a, b, c'})
  1127. (3, ('3',), {'test': ['a', 'b', 'c'], 'max': '3'})
  1128. (3, ('3',), {'test': ["'a'", 'b', 'x=(c)'], 'max': '3'})
  1129. (3, (), {'test': 'x=fish(3)'})
  1130. >>> v = Validator()
  1131. >>> v.check('integer(default=6)', '3')
  1132. 3
  1133. >>> v.check('integer(default=6)', None, True)
  1134. 6
  1135. >>> v.get_default_value('integer(default=6)')
  1136. 6
  1137. >>> v.get_default_value('float(default=6)')
  1138. 6.0
  1139. >>> v.get_default_value('pass(default=None)')
  1140. >>> v.get_default_value("string(default='None')")
  1141. 'None'
  1142. >>> v.get_default_value('pass')
  1143. Traceback (most recent call last):
  1144. KeyError: 'Check "pass" has no default value.'
  1145. >>> v.get_default_value('pass(default=list(1, 2, 3, 4))')
  1146. ['1', '2', '3', '4']
  1147. >>> v = Validator()
  1148. >>> v.check("pass(default=None)", None, True)
  1149. >>> v.check("pass(default='None')", None, True)
  1150. 'None'
  1151. >>> v.check('pass(default="None")', None, True)
  1152. 'None'
  1153. >>> v.check('pass(default=list(1, 2, 3, 4))', None, True)
  1154. ['1', '2', '3', '4']
  1155. Bug test for unicode arguments
  1156. >>> v = Validator()
  1157. >>> v.check(u'string(min=4)', u'test')
  1158. u'test'
  1159. >>> v = Validator()
  1160. >>> v.get_default_value(u'string(min=4, default="1234")')
  1161. u'1234'
  1162. >>> v.check(u'string(min=4, default="1234")', u'test')
  1163. u'test'
  1164. >>> v = Validator()
  1165. >>> default = v.get_default_value('string(default=None)')
  1166. >>> default == None
  1167. 1
  1168. """
  1169. return (value, args, keywargs)
  1170. def _test2():
  1171. """
  1172. >>>
  1173. >>> v = Validator()
  1174. >>> v.get_default_value('string(default="#ff00dd")')
  1175. '#ff00dd'
  1176. >>> v.get_default_value('integer(default=3) # comment')
  1177. 3
  1178. """
  1179. def _test3():
  1180. r"""
  1181. >>> vtor.check('string(default="")', '', missing=True)
  1182. ''
  1183. >>> vtor.check('string(default="\n")', '', missing=True)
  1184. '\n'
  1185. >>> print vtor.check('string(default="\n")', '', missing=True),
  1186. <BLANKLINE>
  1187. >>> vtor.check('string()', '\n')
  1188. '\n'
  1189. >>> vtor.check('string(default="\n\n\n")', '', missing=True)
  1190. '\n\n\n'
  1191. >>> vtor.check('string()', 'random \n text goes here\n\n')
  1192. 'random \n text goes here\n\n'
  1193. >>> vtor.check('string(default=" \nrandom text\ngoes \n here\n\n ")',
  1194. ... '', missing=True)
  1195. ' \nrandom text\ngoes \n here\n\n '
  1196. >>> vtor.check("string(default='\n\n\n')", '', missing=True)
  1197. '\n\n\n'
  1198. >>> vtor.check("option('\n','a','b',default='\n')", '', missing=True)
  1199. '\n'
  1200. >>> vtor.check("string_list()", ['foo', '\n', 'bar'])
  1201. ['foo', '\n', 'bar']
  1202. >>> vtor.check("string_list(default=list('\n'))", '', missing=True)
  1203. ['\n']
  1204. """
  1205. if __name__ == '__main__':
  1206. # run the code tests in doctest format
  1207. import sys
  1208. import doctest
  1209. m = sys.modules.get('__main__')
  1210. globs = m.__dict__.copy()
  1211. globs.update({
  1212. 'vtor': Validator(),
  1213. })
  1214. doctest.testmod(m, globs=globs)