strictyaml icon indicating copy to clipboard operation
strictyaml copied to clipboard

Or validator with Bool and Float causes unexpected results depending on validator order

Open dgg5503 opened this issue 6 years ago • 0 comments

The order of the validators Bool and Float cause the YAML string generated by as_yaml() to differ.

Expected

>>> from strictyaml import *
>>> data = True
>>> schema = Bool() | Float()
>>> yaml = as_document(data, schema)
>>> yaml.as_yaml()
'yes\n...\n'

Unexpected

>>> from strictyaml import *
>>> data = True
>>> schema = Float() | Bool()
>>> yaml = as_document(data, schema)
>>> yaml.as_yaml()
'True\n...\n'

It looks like this may have something to do with the to_yaml() function for the Float validator. The first check that's done in this function is utils.has_number_type(data) where data is the boolean True in the above example cases. This function returns a boolean according to the following statement:

isinstance(value, (int, float, decimal.Decimal))

This will return true for value's which are boolean types since bools in Python inherit from int. See point #6 under review for PEP-0285. Supplemental StackOverflow explanation here.

Interestingly, attempting to parse just from a Float validator does not work:

>>> from strictyaml import *
>>> data = True
>>> schema = Float()
>>> yaml = as_document(data, schema)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\venv\lib\site-packages\strictyaml\parser.py", line 263, in as_document
    return schema(YAMLChunk(schema.to_yaml(data), label=label))
  File "C:\venv\lib\site-packages\strictyaml\scalar.py", line 25, in __call__
    return YAML(chunk, validator=self)
  File "C:\venv\lib\site-packages\strictyaml\representation.py", line 49, in __init__
    self._value = validator.validate(value)
  File "C:\venv\lib\site-packages\strictyaml\scalar.py", line 28, in validate
    return self.validate_scalar(chunk)
  File "C:\venv\lib\site-packages\strictyaml\scalar.py", line 201, in validate_scalar
    chunk.expecting_but_found("when expecting a float")
  File "C:\venv\lib\site-packages\strictyaml\yamllocation.py", line 47, in expecting_but_found
    self,
strictyaml.exceptions.YAMLValidationError: when expecting a float
found arbitrary text
  in "<unicode string>", line 1, column 1:
    'True'

Environment:

  • Python 3.7.3
  • ruamel.yaml 0.16.5
  • strictyaml 1.0.6

dgg5503 avatar Dec 11 '19 21:12 dgg5503