Shuvit game master repo. http://shuvit.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

validate.py 46KB

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