简体   繁体   中英

pytest_schema fails to validate Enum

Given this json response:

api_schema = schema({
    "sts": "OK",
    "values": [
        {
            "mark": And(str, lambda s: len(s) > 1),
            "desc": And(str, lambda s: len(s) > 1),
            "observer": Enum(["testObs", "test"])
            "created": And(int, lambda s: len(str(s)) >= 5),
        }
    ]
})

rsp = {
   "sts":"OK",
   "values":[
      {
         "mark":"test",
         "created":123213213,
         "desc":"Ok",
         "observer":"testObs",
      }
   ]
}

print(api_schema.validate(data=rsp))

Raises:

schema.SchemaError: Key 'values' error:
Or({'mark': And(<class 'str'>, <function <lambda> at 0x0000010A9B6A04A0>), 'desc': And(<class 'str'>, <function <lambda> at 0x0000010A9B858E00>), 'observer': Enum(['testObs', 'BY_CARRIER', 'BY_ALL_DEVICES', 'BY_ALL_USERS', 'BY_USER_ID', 'BY_DEVICE_ID']), 'created': And(<class 'int'>, <function <lambda> at 0x0000010A9B859C60>)}) did not validate {'mark': 'test', 'created': 123213213, 'desc': 'Ok', 'observer': 'testObs'}
Key 'observer' error:
Enum(['testObs', 'BY_CARRIER', 'BY_ALL_DEVICES', 'BY_ALL_USERS', 'BY_USER_ID', 'BY_DEVICE_ID']) did not validate 'testObs'
'testObs' should be instance of 'list'

But it dosent make sense "testObs" is indeed part of "observer": Enum(["testObs"...

Lorem ipsum so i can post: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. "

It seems as if the "Full example" in their Readme is outdated. This PR shows that instead of passing your Enum values as a list, you should pass them as arguments:

"observer": Enum("testObs", "test"),

Putting it back in your example it now works as expected:

from pytest_schema import schema, Enum, And, Regex, Optional, Or

api_schema = schema({
    "sts": "OK",
    "values": [
        {
            "mark": And(str, lambda s: len(s) > 1),
            "desc": And(str, lambda s: len(s) > 1),
            "observer": Enum("testObs", "test"),
            "created": And(int, lambda s: len(str(s)) >= 5),
        }
    ]
})

rsp = {
   "sts":"OK",
   "values":[
      {
         "mark":"test",
         "created":123213213,
         "desc":"Ok",
         "observer":"testObs",
      }
   ]
}

print(api_schema.validate(data=rsp))

=>

❯ python python_test.py
{'sts': 'OK', 'values': [{'mark': 'test', 'created': 123213213, 'desc': 'Ok', 'observer': 'testObs'}]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM