How to use assert_success method in localstack

Best Python code snippet using localstack_python

test_validation.py

Source:test_validation.py Github

copy

Full Screen

...33 assert validator.errors == {field: ['unknown field']}34def test_empty_field_definition(document):35 field = 'name'36 schema = {field: {}}37 assert_success(document, schema)38def test_required_field(schema):39 field = 'a_required_string'40 required_string_extension = {41 'a_required_string': {42 'type': 'string',43 'minlength': 2,44 'maxlength': 10,45 'required': True,46 }47 }48 schema.update(required_string_extension)49 assert_fail(50 {'an_integer': 1},51 schema,52 error=(field, (field, 'required'), errors.REQUIRED_FIELD, True),53 )54def test_nullable_field():55 assert_success({'a_nullable_integer': None})56 assert_success({'a_nullable_integer': 3})57 assert_success({'a_nullable_field_without_type': None})58 assert_fail({'a_nullable_integer': "foo"})59 assert_fail({'an_integer': None})60 assert_fail({'a_not_nullable_field_without_type': None})61def test_nullable_skips_allowed():62 schema = {'role': {'allowed': ['agent', 'client', 'supplier'], 'nullable': True}}63 assert_success({'role': None}, schema)64def test_readonly_field():65 field = 'a_readonly_string'66 assert_fail(67 {field: 'update me if you can'},68 error=(field, (field, 'readonly'), errors.READONLY_FIELD, True),69 )70def test_readonly_field_first_rule():71 # test that readonly rule is checked before any other rule, and blocks.72 # See #63.73 schema = {'a_readonly_number': {'type': 'integer', 'readonly': True, 'max': 1}}74 v = Validator(schema)75 v.validate({'a_readonly_number': 2})76 # it would be a list if there's more than one error; we get a dict77 # instead.78 assert 'read-only' in v.errors['a_readonly_number'][0]79def test_readonly_field_with_default_value():80 schema = {81 'created': {'type': 'string', 'readonly': True, 'default': 'today'},82 'modified': {83 'type': 'string',84 'readonly': True,85 'default_setter': lambda d: d['created'],86 },87 }88 assert_success({}, schema)89 expected_errors = [90 (91 'created',92 ('created', 'readonly'),93 errors.READONLY_FIELD,94 schema['created']['readonly'],95 ),96 (97 'modified',98 ('modified', 'readonly'),99 errors.READONLY_FIELD,100 schema['modified']['readonly'],101 ),102 ]103 assert_fail(104 {'created': 'tomorrow', 'modified': 'today'}, schema, errors=expected_errors105 )106 assert_fail(107 {'created': 'today', 'modified': 'today'}, schema, errors=expected_errors108 )109def test_nested_readonly_field_with_default_value():110 schema = {111 'some_field': {112 'type': 'dict',113 'schema': {114 'created': {'type': 'string', 'readonly': True, 'default': 'today'},115 'modified': {116 'type': 'string',117 'readonly': True,118 'default_setter': lambda d: d['created'],119 },120 },121 }122 }123 assert_success({'some_field': {}}, schema)124 expected_errors = [125 (126 ('some_field', 'created'),127 ('some_field', 'schema', 'created', 'readonly'),128 errors.READONLY_FIELD,129 schema['some_field']['schema']['created']['readonly'],130 ),131 (132 ('some_field', 'modified'),133 ('some_field', 'schema', 'modified', 'readonly'),134 errors.READONLY_FIELD,135 schema['some_field']['schema']['modified']['readonly'],136 ),137 ]138 assert_fail(139 {'some_field': {'created': 'tomorrow', 'modified': 'now'}},140 schema,141 errors=expected_errors,142 )143 assert_fail(144 {'some_field': {'created': 'today', 'modified': 'today'}},145 schema,146 errors=expected_errors,147 )148def test_repeated_readonly(validator):149 # https://github.com/pyeve/cerberus/issues/311150 validator.schema = {'id': {'readonly': True}}151 assert_fail({'id': 0}, validator=validator)152 assert_fail({'id': 0}, validator=validator)153def test_not_a_string():154 assert_bad_type('a_string', 'string', 1)155def test_not_a_binary():156 # 'u' literal prefix produces type `str` in Python 3157 assert_bad_type('a_binary', 'binary', u"i'm not a binary")158def test_not_a_integer():159 assert_bad_type('an_integer', 'integer', "i'm not an integer")160def test_not_a_boolean():161 assert_bad_type('a_boolean', 'boolean', "i'm not a boolean")162def test_not_a_datetime():163 assert_bad_type('a_datetime', 'datetime', "i'm not a datetime")164def test_not_a_float():165 assert_bad_type('a_float', 'float', "i'm not a float")166def test_not_a_number():167 assert_bad_type('a_number', 'number', "i'm not a number")168def test_not_a_list():169 assert_bad_type('a_list_of_values', 'list', "i'm not a list")170def test_not_a_dict():171 assert_bad_type('a_dict', 'dict', "i'm not a dict")172def test_bad_max_length(schema):173 field = 'a_string'174 max_length = schema[field]['maxlength']175 value = "".join(choice(ascii_lowercase) for i in range(max_length + 1))176 assert_fail(177 {field: value},178 error=(179 field,180 (field, 'maxlength'),181 errors.MAX_LENGTH,182 max_length,183 (len(value),),184 ),185 )186def test_bad_max_length_binary(schema):187 field = 'a_binary'188 max_length = schema[field]['maxlength']189 value = b'\x00' * (max_length + 1)190 assert_fail(191 {field: value},192 error=(193 field,194 (field, 'maxlength'),195 errors.MAX_LENGTH,196 max_length,197 (len(value),),198 ),199 )200def test_bad_min_length(schema):201 field = 'a_string'202 min_length = schema[field]['minlength']203 value = "".join(choice(ascii_lowercase) for i in range(min_length - 1))204 assert_fail(205 {field: value},206 error=(207 field,208 (field, 'minlength'),209 errors.MIN_LENGTH,210 min_length,211 (len(value),),212 ),213 )214def test_bad_min_length_binary(schema):215 field = 'a_binary'216 min_length = schema[field]['minlength']217 value = b'\x00' * (min_length - 1)218 assert_fail(219 {field: value},220 error=(221 field,222 (field, 'minlength'),223 errors.MIN_LENGTH,224 min_length,225 (len(value),),226 ),227 )228def test_bad_max_value(schema):229 def assert_bad_max_value(field, inc):230 max_value = schema[field]['max']231 value = max_value + inc232 assert_fail(233 {field: value}, error=(field, (field, 'max'), errors.MAX_VALUE, max_value)234 )235 field = 'an_integer'236 assert_bad_max_value(field, 1)237 field = 'a_float'238 assert_bad_max_value(field, 1.0)239 field = 'a_number'240 assert_bad_max_value(field, 1)241def test_bad_min_value(schema):242 def assert_bad_min_value(field, inc):243 min_value = schema[field]['min']244 value = min_value - inc245 assert_fail(246 {field: value}, error=(field, (field, 'min'), errors.MIN_VALUE, min_value)247 )248 field = 'an_integer'249 assert_bad_min_value(field, 1)250 field = 'a_float'251 assert_bad_min_value(field, 1.0)252 field = 'a_number'253 assert_bad_min_value(field, 1)254def test_bad_schema():255 field = 'a_dict'256 subschema_field = 'address'257 schema = {258 field: {259 'type': 'dict',260 'schema': {261 subschema_field: {'type': 'string'},262 'city': {'type': 'string', 'required': True},263 },264 }265 }266 document = {field: {subschema_field: 34}}267 validator = Validator(schema)268 assert_fail(269 document,270 validator=validator,271 error=(272 field,273 (field, 'schema'),274 errors.MAPPING_SCHEMA,275 validator.schema['a_dict']['schema'],276 ),277 child_errors=[278 (279 (field, subschema_field),280 (field, 'schema', subschema_field, 'type'),281 errors.BAD_TYPE,282 'string',283 ),284 (285 (field, 'city'),286 (field, 'schema', 'city', 'required'),287 errors.REQUIRED_FIELD,288 True,289 ),290 ],291 )292 handler = errors.BasicErrorHandler293 assert field in validator.errors294 assert subschema_field in validator.errors[field][-1]295 assert (296 handler.messages[errors.BAD_TYPE.code].format(constraint='string')297 in validator.errors[field][-1][subschema_field]298 )299 assert 'city' in validator.errors[field][-1]300 assert (301 handler.messages[errors.REQUIRED_FIELD.code]302 in validator.errors[field][-1]['city']303 )304def test_bad_valuesrules():305 field = 'a_dict_with_valuesrules'306 schema_field = 'a_string'307 value = {schema_field: 'not an integer'}308 exp_child_errors = [309 (310 (field, schema_field),311 (field, 'valuesrules', 'type'),312 errors.BAD_TYPE,313 'integer',314 )315 ]316 assert_fail(317 {field: value},318 error=(field, (field, 'valuesrules'), errors.VALUESRULES, {'type': 'integer'}),319 child_errors=exp_child_errors,320 )321def test_bad_list_of_values(validator):322 field = 'a_list_of_values'323 value = ['a string', 'not an integer']324 assert_fail(325 {field: value},326 validator=validator,327 error=(328 field,329 (field, 'items'),330 errors.BAD_ITEMS,331 [{'type': 'string'}, {'type': 'integer'}],332 ),333 child_errors=[334 ((field, 1), (field, 'items', 1, 'type'), errors.BAD_TYPE, 'integer')335 ],336 )337 assert (338 errors.BasicErrorHandler.messages[errors.BAD_TYPE.code].format(339 constraint='integer'340 )341 in validator.errors[field][-1][1]342 )343 value = ['a string', 10, 'an extra item']344 assert_fail(345 {field: value},346 error=(347 field,348 (field, 'items'),349 errors.ITEMS_LENGTH,350 [{'type': 'string'}, {'type': 'integer'}],351 (2, 3),352 ),353 )354def test_bad_list_of_integers():355 field = 'a_list_of_integers'356 value = [34, 'not an integer']357 assert_fail({field: value})358def test_bad_list_of_dicts():359 field = 'a_list_of_dicts'360 map_schema = {361 'sku': {'type': 'string'},362 'price': {'type': 'integer', 'required': True},363 }364 seq_schema = {'type': 'dict', 'schema': map_schema}365 schema = {field: {'type': 'list', 'schema': seq_schema}}366 validator = Validator(schema)367 value = [{'sku': 'KT123', 'price': '100'}]368 document = {field: value}369 assert_fail(370 document,371 validator=validator,372 error=(field, (field, 'schema'), errors.SEQUENCE_SCHEMA, seq_schema),373 child_errors=[374 ((field, 0), (field, 'schema', 'schema'), errors.MAPPING_SCHEMA, map_schema)375 ],376 )377 assert field in validator.errors378 assert 0 in validator.errors[field][-1]379 assert 'price' in validator.errors[field][-1][0][-1]380 exp_msg = errors.BasicErrorHandler.messages[errors.BAD_TYPE.code].format(381 constraint='integer'382 )383 assert exp_msg in validator.errors[field][-1][0][-1]['price']384 value = ["not a dict"]385 exp_child_errors = [386 ((field, 0), (field, 'schema', 'type'), errors.BAD_TYPE, 'dict', ())387 ]388 assert_fail(389 {field: value},390 error=(field, (field, 'schema'), errors.SEQUENCE_SCHEMA, seq_schema),391 child_errors=exp_child_errors,392 )393def test_array_unallowed():394 field = 'an_array'395 value = ['agent', 'client', 'profit']396 assert_fail(397 {field: value},398 error=(399 field,400 (field, 'allowed'),401 errors.UNALLOWED_VALUES,402 ['agent', 'client', 'vendor'],403 ['profit'],404 ),405 )406def test_string_unallowed():407 field = 'a_restricted_string'408 value = 'profit'409 assert_fail(410 {field: value},411 error=(412 field,413 (field, 'allowed'),414 errors.UNALLOWED_VALUE,415 ['agent', 'client', 'vendor'],416 value,417 ),418 )419def test_integer_unallowed():420 field = 'a_restricted_integer'421 value = 2422 assert_fail(423 {field: value},424 error=(field, (field, 'allowed'), errors.UNALLOWED_VALUE, [-1, 0, 1], value),425 )426def test_integer_allowed():427 assert_success({'a_restricted_integer': -1})428def test_validate_update():429 assert_success(430 {431 'an_integer': 100,432 'a_dict': {'address': 'adr'},433 'a_list_of_dicts': [{'sku': 'let'}],434 },435 update=True,436 )437def test_string():438 assert_success({'a_string': 'john doe'})439def test_string_allowed():440 assert_success({'a_restricted_string': 'client'})441def test_integer():442 assert_success({'an_integer': 50})443def test_boolean():444 assert_success({'a_boolean': True})445def test_datetime():446 assert_success({'a_datetime': datetime.now()})447def test_float():448 assert_success({'a_float': 3.5})449 assert_success({'a_float': 1})450def test_number():451 assert_success({'a_number': 3.5})452 assert_success({'a_number': 3})453def test_array():454 assert_success({'an_array': ['agent', 'client']})455def test_set():456 assert_success({'a_set': set(['hello', 1])})457def test_one_of_two_types(validator):458 field = 'one_or_more_strings'459 assert_success({field: 'foo'})460 assert_success({field: ['foo', 'bar']})461 exp_child_errors = [462 ((field, 1), (field, 'schema', 'type'), errors.BAD_TYPE, 'string')463 ]464 assert_fail(465 {field: ['foo', 23]},466 validator=validator,467 error=(field, (field, 'schema'), errors.SEQUENCE_SCHEMA, {'type': 'string'}),468 child_errors=exp_child_errors,469 )470 assert_fail(471 {field: 23},472 error=((field,), (field, 'type'), errors.BAD_TYPE, ['string', 'list']),473 )474 assert validator.errors == {field: [{1: ['must be of string type']}]}475def test_regex(validator):476 field = 'a_regex_email'477 assert_success({field: 'valid.email@gmail.com'}, validator=validator)478 assert_fail(479 {field: 'invalid'},480 update=True,481 error=(482 field,483 (field, 'regex'),484 errors.REGEX_MISMATCH,485 r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$',486 ),487 )488def test_a_list_of_dicts():489 assert_success(490 {491 'a_list_of_dicts': [492 {'sku': 'AK345', 'price': 100},493 {'sku': 'YZ069', 'price': 25},494 ]495 }496 )497def test_a_list_of_values():498 assert_success({'a_list_of_values': ['hello', 100]})499def test_an_array_from_set():500 assert_success({'an_array_from_set': ['agent', 'client']})501def test_a_list_of_integers():502 assert_success({'a_list_of_integers': [99, 100]})503def test_a_dict(schema):504 assert_success({'a_dict': {'address': 'i live here', 'city': 'in my own town'}})505 assert_fail(506 {'a_dict': {'address': 8545}},507 error=(508 'a_dict',509 ('a_dict', 'schema'),510 errors.MAPPING_SCHEMA,511 schema['a_dict']['schema'],512 ),513 child_errors=[514 (515 ('a_dict', 'address'),516 ('a_dict', 'schema', 'address', 'type'),517 errors.BAD_TYPE,518 'string',519 ),520 (521 ('a_dict', 'city'),522 ('a_dict', 'schema', 'city', 'required'),523 errors.REQUIRED_FIELD,524 True,525 ),526 ],527 )528def test_a_dict_with_valuesrules(validator):529 assert_success(530 {'a_dict_with_valuesrules': {'an integer': 99, 'another integer': 100}}531 )532 error = (533 'a_dict_with_valuesrules',534 ('a_dict_with_valuesrules', 'valuesrules'),535 errors.VALUESRULES,536 {'type': 'integer'},537 )538 child_errors = [539 (540 ('a_dict_with_valuesrules', 'a string'),541 ('a_dict_with_valuesrules', 'valuesrules', 'type'),542 errors.BAD_TYPE,543 'integer',544 )545 ]546 assert_fail(547 {'a_dict_with_valuesrules': {'a string': '99'}},548 validator=validator,549 error=error,550 child_errors=child_errors,551 )552 assert 'valuesrules' in validator.schema_error_tree['a_dict_with_valuesrules']553 v = validator.schema_error_tree554 assert len(v['a_dict_with_valuesrules']['valuesrules'].descendants) == 1555# TODO remove 'keyschema' as rule with the next major release556@mark.parametrize('rule', ('keysrules', 'keyschema'))557def test_keysrules(rule):558 schema = {559 'a_dict_with_keysrules': {560 'type': 'dict',561 rule: {'type': 'string', 'regex': '[a-z]+'},562 }563 }564 assert_success({'a_dict_with_keysrules': {'key': 'value'}}, schema=schema)565 assert_fail({'a_dict_with_keysrules': {'KEY': 'value'}}, schema=schema)566def test_a_list_length(schema):567 field = 'a_list_length'568 min_length = schema[field]['minlength']569 max_length = schema[field]['maxlength']570 assert_fail(571 {field: [1] * (min_length - 1)},572 error=(573 field,574 (field, 'minlength'),575 errors.MIN_LENGTH,576 min_length,577 (min_length - 1,),578 ),579 )580 for i in range(min_length, max_length):581 value = [1] * i582 assert_success({field: value})583 assert_fail(584 {field: [1] * (max_length + 1)},585 error=(586 field,587 (field, 'maxlength'),588 errors.MAX_LENGTH,589 max_length,590 (max_length + 1,),591 ),592 )593def test_custom_datatype():594 class MyValidator(Validator):595 def _validate_type_objectid(self, value):596 if re.match('[a-f0-9]{24}', value):597 return True598 schema = {'test_field': {'type': 'objectid'}}599 validator = MyValidator(schema)600 assert_success({'test_field': '50ad188438345b1049c88a28'}, validator=validator)601 assert_fail(602 {'test_field': 'hello'},603 validator=validator,604 error=('test_field', ('test_field', 'type'), errors.BAD_TYPE, 'objectid'),605 )606def test_custom_datatype_rule():607 class MyValidator(Validator):608 def _validate_min_number(self, min_number, field, value):609 """ {'type': 'number'} """610 if value < min_number:611 self._error(field, 'Below the min')612 # TODO replace with TypeDefintion in next major release613 def _validate_type_number(self, value):614 if isinstance(value, int):615 return True616 schema = {'test_field': {'min_number': 1, 'type': 'number'}}617 validator = MyValidator(schema)618 assert_fail(619 {'test_field': '0'},620 validator=validator,621 error=('test_field', ('test_field', 'type'), errors.BAD_TYPE, 'number'),622 )623 assert_fail(624 {'test_field': 0},625 validator=validator,626 error=('test_field', (), errors.CUSTOM, None, ('Below the min',)),627 )628 assert validator.errors == {'test_field': ['Below the min']}629def test_custom_validator():630 class MyValidator(Validator):631 def _validate_isodd(self, isodd, field, value):632 """ {'type': 'boolean'} """633 if isodd and not bool(value & 1):634 self._error(field, 'Not an odd number')635 schema = {'test_field': {'isodd': True}}636 validator = MyValidator(schema)637 assert_success({'test_field': 7}, validator=validator)638 assert_fail(639 {'test_field': 6},640 validator=validator,641 error=('test_field', (), errors.CUSTOM, None, ('Not an odd number',)),642 )643 assert validator.errors == {'test_field': ['Not an odd number']}644@mark.parametrize(645 'value, _type', (('', 'string'), ((), 'list'), ({}, 'dict'), ([], 'list'))646)647def test_empty_values(value, _type):648 field = 'test'649 schema = {field: {'type': _type}}650 document = {field: value}651 assert_success(document, schema)652 schema[field]['empty'] = False653 assert_fail(654 document,655 schema,656 error=(field, (field, 'empty'), errors.EMPTY_NOT_ALLOWED, False),657 )658 schema[field]['empty'] = True659 assert_success(document, schema)660def test_empty_skips_regex(validator):661 schema = {'foo': {'empty': True, 'regex': r'\d?\d\.\d\d', 'type': 'string'}}662 assert validator({'foo': ''}, schema)663def test_ignore_none_values():664 field = 'test'665 schema = {field: {'type': 'string', 'empty': False, 'required': False}}666 document = {field: None}667 # Test normal behaviour668 validator = Validator(schema, ignore_none_values=False)669 assert_fail(document, validator=validator)670 validator.schema[field]['required'] = True671 validator.schema.validate()672 _errors = assert_fail(document, validator=validator)673 assert_not_has_error(674 _errors, field, (field, 'required'), errors.REQUIRED_FIELD, True675 )676 # Test ignore None behaviour677 validator = Validator(schema, ignore_none_values=True)678 validator.schema[field]['required'] = False679 validator.schema.validate()680 assert_success(document, validator=validator)681 validator.schema[field]['required'] = True682 _errors = assert_fail(schema=schema, document=document, validator=validator)683 assert_has_error(_errors, field, (field, 'required'), errors.REQUIRED_FIELD, True)684 assert_not_has_error(_errors, field, (field, 'type'), errors.BAD_TYPE, 'string')685def test_unknown_keys():686 schema = {}687 # test that unknown fields are allowed when allow_unknown is True.688 v = Validator(allow_unknown=True, schema=schema)689 assert_success({"unknown1": True, "unknown2": "yes"}, validator=v)690 # test that unknown fields are allowed only if they meet the691 # allow_unknown schema when provided.692 v.allow_unknown = {'type': 'string'}693 assert_success(document={'name': 'mark'}, validator=v)694 assert_fail({"name": 1}, validator=v)695 # test that unknown fields are not allowed if allow_unknown is False696 v.allow_unknown = False697 assert_fail({'name': 'mark'}, validator=v)698def test_unknown_key_dict(validator):699 # https://github.com/pyeve/cerberus/issues/177700 validator.allow_unknown = True701 document = {'a_dict': {'foo': 'foo_value', 'bar': 25}}702 assert_success(document, {}, validator=validator)703def test_unknown_key_list(validator):704 # https://github.com/pyeve/cerberus/issues/177705 validator.allow_unknown = True706 document = {'a_dict': ['foo', 'bar']}707 assert_success(document, {}, validator=validator)708def test_unknown_keys_list_of_dicts(validator):709 # test that allow_unknown is honored even for subdicts in lists.710 # https://github.com/pyeve/cerberus/issues/67.711 validator.allow_unknown = True712 document = {'a_list_of_dicts': [{'sku': 'YZ069', 'price': 25, 'extra': True}]}713 assert_success(document, validator=validator)714def test_unknown_keys_retain_custom_rules():715 # test that allow_unknown schema respect custom validation rules.716 # https://github.com/pyeve/cerberus/issues/#66.717 class CustomValidator(Validator):718 def _validate_type_foo(self, value):719 if value == "foo":720 return True721 validator = CustomValidator({})722 validator.allow_unknown = {"type": "foo"}723 assert_success(document={"fred": "foo", "barney": "foo"}, validator=validator)724def test_nested_unknown_keys():725 schema = {726 'field1': {727 'type': 'dict',728 'allow_unknown': True,729 'schema': {'nested1': {'type': 'string'}},730 }731 }732 document = {'field1': {'nested1': 'foo', 'arb1': 'bar', 'arb2': 42}}733 assert_success(document=document, schema=schema)734 schema['field1']['allow_unknown'] = {'type': 'string'}735 assert_fail(document=document, schema=schema)736def test_novalidate_noerrors(validator):737 """738 In v0.1.0 and below `self.errors` raised an exception if no739 validation had been performed yet.740 """741 assert validator.errors == {}742def test_callable_validator():743 """744 Validator instance is callable, functions as a shorthand745 passthrough to validate()746 """747 schema = {'test_field': {'type': 'string'}}748 v = Validator(schema)749 assert v.validate({'test_field': 'foo'})750 assert v({'test_field': 'foo'})751 assert not v.validate({'test_field': 1})752 assert not v({'test_field': 1})753def test_dependencies_field():754 schema = {'test_field': {'dependencies': 'foo'}, 'foo': {'type': 'string'}}755 assert_success({'test_field': 'foobar', 'foo': 'bar'}, schema)756 assert_fail({'test_field': 'foobar'}, schema)757def test_dependencies_list():758 schema = {759 'test_field': {'dependencies': ['foo', 'bar']},760 'foo': {'type': 'string'},761 'bar': {'type': 'string'},762 }763 assert_success({'test_field': 'foobar', 'foo': 'bar', 'bar': 'foo'}, schema)764 assert_fail({'test_field': 'foobar', 'foo': 'bar'}, schema)765def test_dependencies_list_with_required_field():766 schema = {767 'test_field': {'required': True, 'dependencies': ['foo', 'bar']},768 'foo': {'type': 'string'},769 'bar': {'type': 'string'},770 }771 # False: all dependencies missing772 assert_fail({'test_field': 'foobar'}, schema)773 # False: one of dependencies missing774 assert_fail({'test_field': 'foobar', 'foo': 'bar'}, schema)775 # False: one of dependencies missing776 assert_fail({'test_field': 'foobar', 'bar': 'foo'}, schema)777 # False: dependencies are validated and field is required778 assert_fail({'foo': 'bar', 'bar': 'foo'}, schema)779 # False: All dependencies are optional but field is still required780 assert_fail({}, schema)781 # True: dependency missing782 assert_fail({'foo': 'bar'}, schema)783 # True: dependencies are validated but field is not required784 schema['test_field']['required'] = False785 assert_success({'foo': 'bar', 'bar': 'foo'}, schema)786def test_dependencies_list_with_subodcuments_fields():787 schema = {788 'test_field': {'dependencies': ['a_dict.foo', 'a_dict.bar']},789 'a_dict': {790 'type': 'dict',791 'schema': {'foo': {'type': 'string'}, 'bar': {'type': 'string'}},792 },793 }794 assert_success(795 {'test_field': 'foobar', 'a_dict': {'foo': 'foo', 'bar': 'bar'}}, schema796 )797 assert_fail({'test_field': 'foobar', 'a_dict': {}}, schema)798 assert_fail({'test_field': 'foobar', 'a_dict': {'foo': 'foo'}}, schema)799def test_dependencies_dict():800 schema = {801 'test_field': {'dependencies': {'foo': 'foo', 'bar': 'bar'}},802 'foo': {'type': 'string'},803 'bar': {'type': 'string'},804 }805 assert_success({'test_field': 'foobar', 'foo': 'foo', 'bar': 'bar'}, schema)806 assert_fail({'test_field': 'foobar', 'foo': 'foo'}, schema)807 assert_fail({'test_field': 'foobar', 'foo': 'bar'}, schema)808 assert_fail({'test_field': 'foobar', 'bar': 'bar'}, schema)809 assert_fail({'test_field': 'foobar', 'bar': 'foo'}, schema)810 assert_fail({'test_field': 'foobar'}, schema)811def test_dependencies_dict_with_required_field():812 schema = {813 'test_field': {'required': True, 'dependencies': {'foo': 'foo', 'bar': 'bar'}},814 'foo': {'type': 'string'},815 'bar': {'type': 'string'},816 }817 # False: all dependencies missing818 assert_fail({'test_field': 'foobar'}, schema)819 # False: one of dependencies missing820 assert_fail({'test_field': 'foobar', 'foo': 'foo'}, schema)821 assert_fail({'test_field': 'foobar', 'bar': 'bar'}, schema)822 # False: dependencies are validated and field is required823 assert_fail({'foo': 'foo', 'bar': 'bar'}, schema)824 # False: All dependencies are optional, but field is still required825 assert_fail({}, schema)826 # False: dependency missing827 assert_fail({'foo': 'bar'}, schema)828 assert_success({'test_field': 'foobar', 'foo': 'foo', 'bar': 'bar'}, schema)829 # True: dependencies are validated but field is not required830 schema['test_field']['required'] = False831 assert_success({'foo': 'bar', 'bar': 'foo'}, schema)832def test_dependencies_field_satisfy_nullable_field():833 # https://github.com/pyeve/cerberus/issues/305834 schema = {'foo': {'nullable': True}, 'bar': {'dependencies': 'foo'}}835 assert_success({'foo': None, 'bar': 1}, schema)836 assert_success({'foo': None}, schema)837 assert_fail({'bar': 1}, schema)838def test_dependencies_field_with_mutually_dependent_nullable_fields():839 # https://github.com/pyeve/cerberus/pull/306840 schema = {841 'foo': {'dependencies': 'bar', 'nullable': True},842 'bar': {'dependencies': 'foo', 'nullable': True},843 }844 assert_success({'foo': None, 'bar': None}, schema)845 assert_success({'foo': 1, 'bar': 1}, schema)846 assert_success({'foo': None, 'bar': 1}, schema)847 assert_fail({'foo': None}, schema)848 assert_fail({'foo': 1}, schema)849def test_dependencies_dict_with_subdocuments_fields():850 schema = {851 'test_field': {852 'dependencies': {'a_dict.foo': ['foo', 'bar'], 'a_dict.bar': 'bar'}853 },854 'a_dict': {855 'type': 'dict',856 'schema': {'foo': {'type': 'string'}, 'bar': {'type': 'string'}},857 },858 }859 assert_success(860 {'test_field': 'foobar', 'a_dict': {'foo': 'foo', 'bar': 'bar'}}, schema861 )862 assert_success(863 {'test_field': 'foobar', 'a_dict': {'foo': 'bar', 'bar': 'bar'}}, schema864 )865 assert_fail({'test_field': 'foobar', 'a_dict': {}}, schema)866 assert_fail(867 {'test_field': 'foobar', 'a_dict': {'foo': 'foo', 'bar': 'foo'}}, schema868 )869 assert_fail({'test_field': 'foobar', 'a_dict': {'bar': 'foo'}}, schema)870 assert_fail({'test_field': 'foobar', 'a_dict': {'bar': 'bar'}}, schema)871def test_root_relative_dependencies():872 # https://github.com/pyeve/cerberus/issues/288873 subschema = {'version': {'dependencies': '^repo'}}874 schema = {'package': {'allow_unknown': True, 'schema': subschema}, 'repo': {}}875 assert_fail(876 {'package': {'repo': 'somewhere', 'version': 0}},877 schema,878 error=('package', ('package', 'schema'), errors.MAPPING_SCHEMA, subschema),879 child_errors=[880 (881 ('package', 'version'),882 ('package', 'schema', 'version', 'dependencies'),883 errors.DEPENDENCIES_FIELD,884 '^repo',885 ('^repo',),886 )887 ],888 )889 assert_success({'repo': 'somewhere', 'package': {'version': 1}}, schema)890def test_dependencies_errors():891 v = Validator(892 {893 'field1': {'required': False},894 'field2': {'required': True, 'dependencies': {'field1': ['one', 'two']}},895 }896 )897 assert_fail(898 {'field1': 'three', 'field2': 7},899 validator=v,900 error=(901 'field2',902 ('field2', 'dependencies'),903 errors.DEPENDENCIES_FIELD_VALUE,904 {'field1': ['one', 'two']},905 ({'field1': 'three'},),906 ),907 )908def test_options_passed_to_nested_validators(validator):909 validator.schema = {910 'sub_dict': {'type': 'dict', 'schema': {'foo': {'type': 'string'}}}911 }912 validator.allow_unknown = True913 assert_success({'sub_dict': {'foo': 'bar', 'unknown': True}}, validator=validator)914def test_self_root_document():915 """ Make sure self.root_document is always the root document.916 See:917 * https://github.com/pyeve/cerberus/pull/42918 * https://github.com/pyeve/eve/issues/295919 """920 class MyValidator(Validator):921 def _validate_root_doc(self, root_doc, field, value):922 """ {'type': 'boolean'} """923 if 'sub' not in self.root_document or len(self.root_document['sub']) != 2:924 self._error(field, 'self.context is not the root doc!')925 schema = {926 'sub': {927 'type': 'list',928 'root_doc': True,929 'schema': {930 'type': 'dict',931 'schema': {'foo': {'type': 'string', 'root_doc': True}},932 },933 }934 }935 assert_success(936 {'sub': [{'foo': 'bar'}, {'foo': 'baz'}]}, validator=MyValidator(schema)937 )938def test_validator_rule(validator):939 def validate_name(field, value, error):940 if not value.islower():941 error(field, 'must be lowercase')942 validator.schema = {943 'name': {'validator': validate_name},944 'age': {'type': 'integer'},945 }946 assert_fail(947 {'name': 'ItsMe', 'age': 2},948 validator=validator,949 error=('name', (), errors.CUSTOM, None, ('must be lowercase',)),950 )951 assert validator.errors == {'name': ['must be lowercase']}952 assert_success({'name': 'itsme', 'age': 2}, validator=validator)953def test_validated(validator):954 validator.schema = {'property': {'type': 'string'}}955 document = {'property': 'string'}956 assert validator.validated(document) == document957 document = {'property': 0}958 assert validator.validated(document) is None959def test_anyof():960 # prop1 must be either a number between 0 and 10961 schema = {'prop1': {'min': 0, 'max': 10}}962 doc = {'prop1': 5}963 assert_success(doc, schema)964 # prop1 must be either a number between 0 and 10 or 100 and 110965 schema = {'prop1': {'anyof': [{'min': 0, 'max': 10}, {'min': 100, 'max': 110}]}}966 doc = {'prop1': 105}967 assert_success(doc, schema)968 # prop1 must be either a number between 0 and 10 or 100 and 110969 schema = {'prop1': {'anyof': [{'min': 0, 'max': 10}, {'min': 100, 'max': 110}]}}970 doc = {'prop1': 50}971 assert_fail(doc, schema)972 # prop1 must be an integer that is either be973 # greater than or equal to 0, or greater than or equal to 10974 schema = {'prop1': {'type': 'integer', 'anyof': [{'min': 0}, {'min': 10}]}}975 assert_success({'prop1': 10}, schema)976 # test that intermediate schemas do not sustain977 assert 'type' not in schema['prop1']['anyof'][0]978 assert 'type' not in schema['prop1']['anyof'][1]979 assert 'allow_unknown' not in schema['prop1']['anyof'][0]980 assert 'allow_unknown' not in schema['prop1']['anyof'][1]981 assert_success({'prop1': 5}, schema)982 exp_child_errors = [983 (('prop1',), ('prop1', 'anyof', 0, 'min'), errors.MIN_VALUE, 0),984 (('prop1',), ('prop1', 'anyof', 1, 'min'), errors.MIN_VALUE, 10),985 ]986 assert_fail(987 {'prop1': -1},988 schema,989 error=(('prop1',), ('prop1', 'anyof'), errors.ANYOF, [{'min': 0}, {'min': 10}]),990 child_errors=exp_child_errors,991 )992 doc = {'prop1': 5.5}993 assert_fail(doc, schema)994 doc = {'prop1': '5.5'}995 assert_fail(doc, schema)996def test_allof():997 # prop1 has to be a float between 0 and 10998 schema = {'prop1': {'allof': [{'type': 'float'}, {'min': 0}, {'max': 10}]}}999 doc = {'prop1': -1}1000 assert_fail(doc, schema)1001 doc = {'prop1': 5}1002 assert_success(doc, schema)1003 doc = {'prop1': 11}1004 assert_fail(doc, schema)1005 # prop1 has to be a float and an integer1006 schema = {'prop1': {'allof': [{'type': 'float'}, {'type': 'integer'}]}}1007 doc = {'prop1': 11}1008 assert_success(doc, schema)1009 doc = {'prop1': 11.5}1010 assert_fail(doc, schema)1011 doc = {'prop1': '11'}1012 assert_fail(doc, schema)1013def test_unicode_allowed():1014 # issue 2801015 doc = {'letters': u'♄εℓł☺'}1016 schema = {'letters': {'type': 'string', 'allowed': ['a', 'b', 'c']}}1017 assert_fail(doc, schema)1018 schema = {'letters': {'type': 'string', 'allowed': [u'♄εℓł☺']}}1019 assert_success(doc, schema)1020 schema = {'letters': {'type': 'string', 'allowed': ['♄εℓł☺']}}1021 doc = {'letters': '♄εℓł☺'}1022 assert_success(doc, schema)1023@mark.skipif(sys.version_info[0] < 3, reason='requires python 3.x')1024def test_unicode_allowed_py3():1025 """ All strings are unicode in Python 3.x. Input doc and schema1026 have equal strings and validation yield success."""1027 # issue 2801028 doc = {'letters': u'♄εℓł☺'}1029 schema = {'letters': {'type': 'string', 'allowed': ['♄εℓł☺']}}1030 assert_success(doc, schema)1031@mark.skipif(sys.version_info[0] > 2, reason='requires python 2.x')1032def test_unicode_allowed_py2():1033 """ Python 2.x encodes value of allowed using default encoding if1034 the string includes characters outside ASCII range. Produced string1035 does not match input which is an unicode string."""1036 # issue 2801037 doc = {'letters': u'♄εℓł☺'}1038 schema = {'letters': {'type': 'string', 'allowed': ['♄εℓł☺']}}1039 assert_fail(doc, schema)1040def test_oneof():1041 # prop1 can only only be:1042 # - greater than 101043 # - greater than 01044 # - equal to -5, 5, or 151045 schema = {1046 'prop1': {1047 'type': 'integer',1048 'oneof': [{'min': 0}, {'min': 10}, {'allowed': [-5, 5, 15]}],1049 }1050 }1051 # document is not valid1052 # prop1 not greater than 0, 10 or equal to -51053 doc = {'prop1': -1}1054 assert_fail(doc, schema)1055 # document is valid1056 # prop1 is less then 0, but is -51057 doc = {'prop1': -5}1058 assert_success(doc, schema)1059 # document is valid1060 # prop1 greater than 01061 doc = {'prop1': 1}1062 assert_success(doc, schema)1063 # document is not valid1064 # prop1 is greater than 01065 # and equal to 51066 doc = {'prop1': 5}1067 assert_fail(doc, schema)1068 # document is not valid1069 # prop1 is greater than 01070 # and greater than 101071 doc = {'prop1': 11}1072 assert_fail(doc, schema)1073 # document is not valid1074 # prop1 is greater than 01075 # and greater than 101076 # and equal to 151077 doc = {'prop1': 15}1078 assert_fail(doc, schema)1079def test_noneof():1080 # prop1 can not be:1081 # - greater than 101082 # - greater than 01083 # - equal to -5, 5, or 151084 schema = {1085 'prop1': {1086 'type': 'integer',1087 'noneof': [{'min': 0}, {'min': 10}, {'allowed': [-5, 5, 15]}],1088 }1089 }1090 # document is valid1091 doc = {'prop1': -1}1092 assert_success(doc, schema)1093 # document is not valid1094 # prop1 is equal to -51095 doc = {'prop1': -5}1096 assert_fail(doc, schema)1097 # document is not valid1098 # prop1 greater than 01099 doc = {'prop1': 1}1100 assert_fail(doc, schema)1101 # document is not valid1102 doc = {'prop1': 5}1103 assert_fail(doc, schema)1104 # document is not valid1105 doc = {'prop1': 11}1106 assert_fail(doc, schema)1107 # document is not valid1108 # and equal to 151109 doc = {'prop1': 15}1110 assert_fail(doc, schema)1111def test_anyof_allof():1112 # prop1 can be any number outside of [0-10]1113 schema = {1114 'prop1': {1115 'allof': [1116 {'anyof': [{'type': 'float'}, {'type': 'integer'}]},1117 {'anyof': [{'min': 10}, {'max': 0}]},1118 ]1119 }1120 }1121 doc = {'prop1': 11}1122 assert_success(doc, schema)1123 doc = {'prop1': -1}1124 assert_success(doc, schema)1125 doc = {'prop1': 5}1126 assert_fail(doc, schema)1127 doc = {'prop1': 11.5}1128 assert_success(doc, schema)1129 doc = {'prop1': -1.5}1130 assert_success(doc, schema)1131 doc = {'prop1': 5.5}1132 assert_fail(doc, schema)1133 doc = {'prop1': '5.5'}1134 assert_fail(doc, schema)1135def test_anyof_schema(validator):1136 # test that a list of schemas can be specified.1137 valid_parts = [1138 {'schema': {'model number': {'type': 'string'}, 'count': {'type': 'integer'}}},1139 {'schema': {'serial number': {'type': 'string'}, 'count': {'type': 'integer'}}},1140 ]1141 valid_item = {'type': ['dict', 'string'], 'anyof': valid_parts}1142 schema = {'parts': {'type': 'list', 'schema': valid_item}}1143 document = {1144 'parts': [1145 {'model number': 'MX-009', 'count': 100},1146 {'serial number': '898-001'},1147 'misc',1148 ]1149 }1150 # document is valid. each entry in 'parts' matches a type or schema1151 assert_success(document, schema, validator=validator)1152 document['parts'].append({'product name': "Monitors", 'count': 18})1153 # document is invalid. 'product name' does not match any valid schemas1154 assert_fail(document, schema, validator=validator)1155 document['parts'].pop()1156 # document is valid again1157 assert_success(document, schema, validator=validator)1158 document['parts'].append({'product name': "Monitors", 'count': 18})1159 document['parts'].append(10)1160 # and invalid. numbers are not allowed.1161 exp_child_errors = [1162 (('parts', 3), ('parts', 'schema', 'anyof'), errors.ANYOF, valid_parts),1163 (1164 ('parts', 4),1165 ('parts', 'schema', 'type'),1166 errors.BAD_TYPE,1167 ['dict', 'string'],1168 ),1169 ]1170 _errors = assert_fail(1171 document,1172 schema,1173 validator=validator,1174 error=('parts', ('parts', 'schema'), errors.SEQUENCE_SCHEMA, valid_item),1175 child_errors=exp_child_errors,1176 )1177 assert_not_has_error(1178 _errors, ('parts', 4), ('parts', 'schema', 'anyof'), errors.ANYOF, valid_parts1179 )1180 # tests errors.BasicErrorHandler's tree representation1181 v_errors = validator.errors1182 assert 'parts' in v_errors1183 assert 3 in v_errors['parts'][-1]1184 assert v_errors['parts'][-1][3][0] == "no definitions validate"1185 scope = v_errors['parts'][-1][3][-1]1186 assert 'anyof definition 0' in scope1187 assert 'anyof definition 1' in scope1188 assert scope['anyof definition 0'] == [{"product name": ["unknown field"]}]1189 assert scope['anyof definition 1'] == [{"product name": ["unknown field"]}]1190 assert v_errors['parts'][-1][4] == ["must be of ['dict', 'string'] type"]1191def test_anyof_2():1192 # these two schema should be the same1193 schema1 = {1194 'prop': {1195 'anyof': [1196 {'type': 'dict', 'schema': {'val': {'type': 'integer'}}},1197 {'type': 'dict', 'schema': {'val': {'type': 'string'}}},1198 ]1199 }1200 }1201 schema2 = {1202 'prop': {1203 'type': 'dict',1204 'anyof': [1205 {'schema': {'val': {'type': 'integer'}}},1206 {'schema': {'val': {'type': 'string'}}},1207 ],1208 }1209 }1210 doc = {'prop': {'val': 0}}1211 assert_success(doc, schema1)1212 assert_success(doc, schema2)1213 doc = {'prop': {'val': '0'}}1214 assert_success(doc, schema1)1215 assert_success(doc, schema2)1216 doc = {'prop': {'val': 1.1}}1217 assert_fail(doc, schema1)1218 assert_fail(doc, schema2)1219def test_anyof_type():1220 schema = {'anyof_type': {'anyof_type': ['string', 'integer']}}1221 assert_success({'anyof_type': 'bar'}, schema)1222 assert_success({'anyof_type': 23}, schema)1223def test_oneof_schema():1224 schema = {1225 'oneof_schema': {1226 'type': 'dict',1227 'oneof_schema': [1228 {'digits': {'type': 'integer', 'min': 0, 'max': 99}},1229 {'text': {'type': 'string', 'regex': '^[0-9]{2}$'}},1230 ],1231 }1232 }1233 assert_success({'oneof_schema': {'digits': 19}}, schema)1234 assert_success({'oneof_schema': {'text': '84'}}, schema)1235 assert_fail({'oneof_schema': {'digits': 19, 'text': '84'}}, schema)1236def test_nested_oneof_type():1237 schema = {1238 'nested_oneof_type': {'valuesrules': {'oneof_type': ['string', 'integer']}}1239 }1240 assert_success({'nested_oneof_type': {'foo': 'a'}}, schema)1241 assert_success({'nested_oneof_type': {'bar': 3}}, schema)1242def test_nested_oneofs(validator):1243 validator.schema = {1244 'abc': {1245 'type': 'dict',1246 'oneof_schema': [1247 {1248 'foo': {1249 'type': 'dict',1250 'schema': {'bar': {'oneof_type': ['integer', 'float']}},1251 }1252 },1253 {'baz': {'type': 'string'}},1254 ],1255 }1256 }1257 document = {'abc': {'foo': {'bar': 'bad'}}}1258 expected_errors = {1259 'abc': [1260 'none or more than one rule validate',1261 {1262 'oneof definition 0': [1263 {1264 'foo': [1265 {1266 'bar': [1267 'none or more than one rule validate',1268 {1269 'oneof definition 0': [1270 'must be of integer type'1271 ],1272 'oneof definition 1': ['must be of float type'],1273 },1274 ]1275 }1276 ]1277 }1278 ],1279 'oneof definition 1': [{'foo': ['unknown field']}],1280 },1281 ]1282 }1283 assert_fail(document, validator=validator)1284 assert validator.errors == expected_errors1285def test_no_of_validation_if_type_fails(validator):1286 valid_parts = [1287 {'schema': {'model number': {'type': 'string'}, 'count': {'type': 'integer'}}},1288 {'schema': {'serial number': {'type': 'string'}, 'count': {'type': 'integer'}}},1289 ]1290 validator.schema = {'part': {'type': ['dict', 'string'], 'anyof': valid_parts}}1291 document = {'part': 10}1292 _errors = assert_fail(document, validator=validator)1293 assert len(_errors) == 11294def test_issue_107(validator):1295 schema = {1296 'info': {1297 'type': 'dict',1298 'schema': {'name': {'type': 'string', 'required': True}},1299 }1300 }1301 document = {'info': {'name': 'my name'}}1302 assert_success(document, schema, validator=validator)1303 v = Validator(schema)1304 assert_success(document, schema, v)1305 # it once was observed that this behaves other than the previous line1306 assert v.validate(document)1307def test_dont_type_validate_nulled_values(validator):1308 assert_fail({'an_integer': None}, validator=validator)1309 assert validator.errors == {'an_integer': ['null value not allowed']}1310def test_dependencies_error(validator):1311 schema = {1312 'field1': {'required': False},1313 'field2': {'required': True, 'dependencies': {'field1': ['one', 'two']}},1314 }1315 validator.validate({'field2': 7}, schema)1316 exp_msg = errors.BasicErrorHandler.messages[1317 errors.DEPENDENCIES_FIELD_VALUE.code1318 ].format(field='field2', constraint={'field1': ['one', 'two']})1319 assert validator.errors == {'field2': [exp_msg]}1320def test_dependencies_on_boolean_field_with_one_value():1321 # https://github.com/pyeve/cerberus/issues/1381322 schema = {1323 'deleted': {'type': 'boolean'},1324 'text': {'dependencies': {'deleted': False}},1325 }1326 try:1327 assert_success({'text': 'foo', 'deleted': False}, schema)1328 assert_fail({'text': 'foo', 'deleted': True}, schema)1329 assert_fail({'text': 'foo'}, schema)1330 except TypeError as e:1331 if str(e) == "argument of type 'bool' is not iterable":1332 raise AssertionError(1333 "Bug #138 still exists, couldn't use boolean in dependency "1334 "without putting it in a list.\n"1335 "'some_field': True vs 'some_field: [True]"1336 )1337 else:1338 raise1339def test_dependencies_on_boolean_field_with_value_in_list():1340 # https://github.com/pyeve/cerberus/issues/1381341 schema = {1342 'deleted': {'type': 'boolean'},1343 'text': {'dependencies': {'deleted': [False]}},1344 }1345 assert_success({'text': 'foo', 'deleted': False}, schema)1346 assert_fail({'text': 'foo', 'deleted': True}, schema)1347 assert_fail({'text': 'foo'}, schema)1348def test_document_path():1349 class DocumentPathTester(Validator):1350 def _validate_trail(self, constraint, field, value):1351 """ {'type': 'boolean'} """1352 test_doc = self.root_document1353 for crumb in self.document_path:1354 test_doc = test_doc[crumb]1355 assert test_doc == self.document1356 v = DocumentPathTester()1357 schema = {'foo': {'schema': {'bar': {'trail': True}}}}1358 document = {'foo': {'bar': {}}}1359 assert_success(document, schema, validator=v)1360def test_excludes():1361 schema = {1362 'this_field': {'type': 'dict', 'excludes': 'that_field'},1363 'that_field': {'type': 'dict'},1364 }1365 assert_success({'this_field': {}}, schema)1366 assert_success({'that_field': {}}, schema)1367 assert_success({}, schema)1368 assert_fail({'that_field': {}, 'this_field': {}}, schema)1369def test_mutual_excludes():1370 schema = {1371 'this_field': {'type': 'dict', 'excludes': 'that_field'},1372 'that_field': {'type': 'dict', 'excludes': 'this_field'},1373 }1374 assert_success({'this_field': {}}, schema)1375 assert_success({'that_field': {}}, schema)1376 assert_success({}, schema)1377 assert_fail({'that_field': {}, 'this_field': {}}, schema)1378def test_required_excludes():1379 schema = {1380 'this_field': {'type': 'dict', 'excludes': 'that_field', 'required': True},1381 'that_field': {'type': 'dict', 'excludes': 'this_field', 'required': True},1382 }1383 assert_success({'this_field': {}}, schema, update=False)1384 assert_success({'that_field': {}}, schema, update=False)1385 assert_fail({}, schema)1386 assert_fail({'that_field': {}, 'this_field': {}}, schema)1387def test_multiples_exclusions():1388 schema = {1389 'this_field': {'type': 'dict', 'excludes': ['that_field', 'bazo_field']},1390 'that_field': {'type': 'dict', 'excludes': 'this_field'},1391 'bazo_field': {'type': 'dict'},1392 }1393 assert_success({'this_field': {}}, schema)1394 assert_success({'that_field': {}}, schema)1395 assert_fail({'this_field': {}, 'that_field': {}}, schema)1396 assert_fail({'this_field': {}, 'bazo_field': {}}, schema)1397 assert_fail({'that_field': {}, 'this_field': {}, 'bazo_field': {}}, schema)1398 assert_success({'that_field': {}, 'bazo_field': {}}, schema)1399def test_bad_excludes_fields(validator):1400 validator.schema = {1401 'this_field': {1402 'type': 'dict',1403 'excludes': ['that_field', 'bazo_field'],1404 'required': True,1405 },1406 'that_field': {'type': 'dict', 'excludes': 'this_field', 'required': True},1407 }1408 assert_fail({'that_field': {}, 'this_field': {}}, validator=validator)1409 handler = errors.BasicErrorHandler1410 assert validator.errors == {1411 'that_field': [1412 handler.messages[errors.EXCLUDES_FIELD.code].format(1413 "'this_field'", field="that_field"1414 )1415 ],1416 'this_field': [1417 handler.messages[errors.EXCLUDES_FIELD.code].format(1418 "'that_field', 'bazo_field'", field="this_field"1419 )1420 ],1421 }1422def test_boolean_is_not_a_number():1423 # https://github.com/pyeve/cerberus/issues/1441424 assert_fail({'value': True}, {'value': {'type': 'number'}})1425def test_min_max_date():1426 schema = {'date': {'min': date(1900, 1, 1), 'max': date(1999, 12, 31)}}1427 assert_success({'date': date(1945, 5, 8)}, schema)1428 assert_fail({'date': date(1871, 5, 10)}, schema)1429def test_dict_length():1430 schema = {'dict': {'minlength': 1}}1431 assert_fail({'dict': {}}, schema)1432 assert_success({'dict': {'foo': 'bar'}}, schema)1433def test_forbidden():1434 schema = {'user': {'forbidden': ['root', 'admin']}}1435 assert_fail({'user': 'admin'}, schema)1436 assert_success({'user': 'alice'}, schema)1437def test_forbidden_number():1438 schema = {'amount': {'forbidden': (0, 0.0)}}1439 assert_fail({'amount': 0}, schema)1440 assert_fail({'amount': 0.0}, schema)1441def test_mapping_with_sequence_schema():1442 schema = {'list': {'schema': {'allowed': ['a', 'b', 'c']}}}1443 document = {'list': {'is_a': 'mapping'}}1444 assert_fail(1445 document,1446 schema,1447 error=(1448 'list',1449 ('list', 'schema'),1450 errors.BAD_TYPE_FOR_SCHEMA,1451 schema['list']['schema'],1452 ),1453 )1454def test_sequence_with_mapping_schema():1455 schema = {'list': {'schema': {'foo': {'allowed': ['a', 'b', 'c']}}, 'type': 'dict'}}1456 document = {'list': ['a', 'b', 'c']}1457 assert_fail(document, schema)1458def test_type_error_aborts_validation():1459 schema = {'foo': {'type': 'string', 'allowed': ['a']}}1460 document = {'foo': 0}1461 assert_fail(1462 document, schema, error=('foo', ('foo', 'type'), errors.BAD_TYPE, 'string')1463 )1464def test_dependencies_in_oneof():1465 # https://github.com/pyeve/cerberus/issues/2411466 schema = {1467 'a': {1468 'type': 'integer',1469 'oneof': [1470 {'allowed': [1], 'dependencies': 'b'},1471 {'allowed': [2], 'dependencies': 'c'},1472 ],1473 },1474 'b': {},1475 'c': {},1476 }1477 assert_success({'a': 1, 'b': 'foo'}, schema)1478 assert_success({'a': 2, 'c': 'bar'}, schema)1479 assert_fail({'a': 1, 'c': 'foo'}, schema)1480 assert_fail({'a': 2, 'b': 'bar'}, schema)1481def test_allow_unknown_with_oneof_rules(validator):1482 # https://github.com/pyeve/cerberus/issues/2511483 schema = {1484 'test': {1485 'oneof': [1486 {1487 'type': 'dict',1488 'allow_unknown': True,1489 'schema': {'known': {'type': 'string'}},1490 },1491 {'type': 'dict', 'schema': {'known': {'type': 'string'}}},1492 ]1493 }1494 }1495 # check regression and that allow unknown does not cause any different1496 # than expected behaviour for one-of.1497 document = {'test': {'known': 's'}}1498 validator(document, schema)1499 _errors = validator._errors1500 assert len(_errors) == 11501 assert_has_error(1502 _errors, 'test', ('test', 'oneof'), errors.ONEOF, schema['test']['oneof']1503 )1504 assert len(_errors[0].child_errors) == 01505 # check that allow_unknown is actually applied1506 document = {'test': {'known': 's', 'unknown': 'asd'}}1507 assert_success(document, validator=validator)1508@mark.parametrize('constraint', (('Graham Chapman', 'Eric Idle'), 'Terry Gilliam'))1509def test_contains(constraint):1510 validator = Validator({'actors': {'contains': constraint}})1511 document = {'actors': ('Graham Chapman', 'Eric Idle', 'Terry Gilliam')}1512 assert validator(document)1513 document = {'actors': ('Eric idle', 'Terry Jones', 'John Cleese', 'Michael Palin')}1514 assert not validator(document)1515 assert errors.MISSING_MEMBERS in validator.document_error_tree['actors']1516 missing_actors = validator.document_error_tree['actors'][1517 errors.MISSING_MEMBERS1518 ].info[0]1519 assert any(x in missing_actors for x in ('Eric Idle', 'Terry Gilliam'))1520def test_require_all_simple():1521 schema = {'foo': {'type': 'string'}}1522 validator = Validator(require_all=True)1523 assert_fail(1524 {},1525 schema,1526 validator,1527 error=('foo', '__require_all__', errors.REQUIRED_FIELD, True),1528 )1529 assert_success({'foo': 'bar'}, schema, validator)1530 validator.require_all = False1531 assert_success({}, schema, validator)1532 assert_success({'foo': 'bar'}, schema, validator)1533def test_require_all_override_by_required():1534 schema = {'foo': {'type': 'string', 'required': False}}1535 validator = Validator(require_all=True)1536 assert_success({}, schema, validator)1537 assert_success({'foo': 'bar'}, schema, validator)1538 validator.require_all = False1539 assert_success({}, schema, validator)1540 assert_success({'foo': 'bar'}, schema, validator)1541 schema = {'foo': {'type': 'string', 'required': True}}1542 validator.require_all = True1543 assert_fail(1544 {},1545 schema,1546 validator,1547 error=('foo', ('foo', 'required'), errors.REQUIRED_FIELD, True),1548 )1549 assert_success({'foo': 'bar'}, schema, validator)1550 validator.require_all = False1551 assert_fail(1552 {},1553 schema,1554 validator,1555 error=('foo', ('foo', 'required'), errors.REQUIRED_FIELD, True),1556 )1557 assert_success({'foo': 'bar'}, schema, validator)1558@mark.parametrize(1559 "validator_require_all, sub_doc_require_all",1560 list(itertools.product([True, False], repeat=2)),1561)1562def test_require_all_override_by_subdoc_require_all(1563 validator_require_all, sub_doc_require_all1564):1565 sub_schema = {"bar": {"type": "string"}}1566 schema = {1567 "foo": {1568 "type": "dict",1569 "require_all": sub_doc_require_all,1570 "schema": sub_schema,1571 }1572 }1573 validator = Validator(require_all=validator_require_all)1574 assert_success({"foo": {"bar": "baz"}}, schema, validator)1575 if validator_require_all:1576 assert_fail({}, schema, validator)1577 else:1578 assert_success({}, schema, validator)1579 if sub_doc_require_all:1580 assert_fail({"foo": {}}, schema, validator)1581 else:1582 assert_success({"foo": {}}, schema, validator)1583def test_require_all_and_exclude():1584 schema = {1585 'foo': {'type': 'string', 'excludes': 'bar'},1586 'bar': {'type': 'string', 'excludes': 'foo'},1587 }1588 validator = Validator(require_all=True)1589 assert_fail(1590 {},1591 schema,1592 validator,1593 errors=[1594 ('foo', '__require_all__', errors.REQUIRED_FIELD, True),1595 ('bar', '__require_all__', errors.REQUIRED_FIELD, True),1596 ],1597 )1598 assert_success({'foo': 'value'}, schema, validator)1599 assert_success({'bar': 'value'}, schema, validator)1600 assert_fail({'foo': 'value', 'bar': 'value'}, schema, validator)1601 validator.require_all = False1602 assert_success({}, schema, validator)1603 assert_success({'foo': 'value'}, schema, validator)1604 assert_success({'bar': 'value'}, schema, validator)...

Full Screen

Full Screen

fs_test.py

Source:fs_test.py Github

copy

Full Screen

...18from qumulo.lib.request import CONTENT_TYPE_BINARY19class GetAttrRestTest(unittest.TestCase, RestTest):20 def setUp(self):21 RestTest.setUp(self, qumulo.rest.fs.get_attr, "GET")22 def assert_success(self, exp_uri, path=None, id_=None):23 self.run_command(path=path, id_=id_)24 self.assertCalledWith(exp_uri)25 def test_success(self):26 self.assert_success("/v1/fs/path/%2Ffoo?attributes", path="foo")27 self.assert_success("/v1/fs/id/1?attributes", id_="1")28 def test_empty_path(self):29 self.run_command("")30 self.assertCalledWith("/v1/fs/path/%2F?attributes")31class SetAttrRestTest(unittest.TestCase, RestTest):32 def setUp(self):33 RestTest.setUp(self, qumulo.rest.fs.set_attr, "PUT")34 self.mode = 'hung over'35 self.owner = 'Jeff Daniels'36 self.group = 'Bad Whiskey'37 self.size = 'far too large'38 self.modification_time = 'recent'39 self.change_time = 'dunno'40 self.body = {41 'mode': self.mode,42 'owner': self.owner,43 'group': self.group,44 'size': self.size,45 'modification_time': self.modification_time,46 'change_time': self.change_time,47 }48 self.if_match = 'etag'49 def test_success(self):50 self.run_command(self.mode, self.owner, self.group, self.size,51 self.modification_time, self.change_time, "foo", None,52 self.if_match)53 self.assertCalledWith("/v1/fs/path/%2Ffoo?attributes",54 body=self.body, if_match=self.if_match)55 def test_success_by_id(self):56 self.run_command(self.mode, self.owner, self.group, self.size,57 self.modification_time, self.change_time, None, "1", self.if_match)58 self.assertCalledWith("/v1/fs/id/1?attributes",59 body=self.body, if_match=self.if_match)60 def test_empty_path(self):61 self.run_command(self.mode, self.owner, self.group, self.size,62 self.modification_time, self.change_time, "", None, self.if_match)63 self.assertCalledWith("/v1/fs/path/%2F?attributes",64 body=self.body, if_match=self.if_match)65class SetFileAttrRestTest(unittest.TestCase, RestTest):66 def setUp(self):67 RestTest.setUp(self, qumulo.rest.fs.set_file_attr, "PATCH")68 self.mode = 'chipper'69 self.owner = 'Pizza Hut'70 self.group = 'Food-ish'71 self.size = '15 inches'72 self.creation_time = 'Under 30 min'73 self.modification_time = 'Chewed recently'74 self.change_time = 'Subject to digestion'75 self.body = {76 'mode': self.mode,77 'owner': self.owner,78 'group': self.group,79 'size': self.size,80 'creation_time': self.creation_time,81 'modification_time': self.modification_time,82 'change_time': self.change_time,83 }84 self.if_match = 'Want pizza'85 def test_success(self):86 self.run_command(self.mode, self.owner, self.group, self.size,87 self.creation_time, self.modification_time, self.change_time, "2",88 self.if_match)89 self.assertCalledWith("/v1/fs/file/2/attributes",90 body=self.body, if_match=self.if_match)91ACL_QUERY = [('acl', None)]92class GetAclRestTest(unittest.TestCase, RestTest):93 def setUp(self):94 RestTest.setUp(self, qumulo.rest.fs.get_acl, "GET")95 def assert_success(self, exp_uri, path=None, id_=None):96 self.run_command(path=path, id_=id_)97 self.assertCalledWith(exp_uri)98 def test_success(self):99 self.assert_success("/v1/fs/path/%2Ffoo?acl", path="foo")100 self.assert_success("/v1/fs/id/1?acl", id_="1")101 def test_empty_path(self):102 self.run_command("")103 self.assertCalledWith("/v1/fs/path/%2F?acl")104class SetAclRestTest(unittest.TestCase, RestTest):105 def setUp(self):106 RestTest.setUp(self, qumulo.rest.fs.set_acl, "PUT")107 def test_acl(self):108 aces = ['wild', 'mild', 'jacky']109 control = ['none', 'some', 'freak']110 body = {'control': control, 'aces': aces}111 if_match = '!'112 self.run_command(path="foo", aces=aces, control=control,113 if_match=if_match)114 self.assertCalledWith("/v1/fs/path/%2Ffoo?acl", body=body,115 if_match=if_match)116 self.run_command(id_="1", aces=aces, control=control, if_match=if_match)117 self.assertCalledWith("/v1/fs/id/1?acl", body=body, if_match=if_match)118 def test_only_one(self):119 aces = mock.Mock()120 if_match = mock.Mock()121 control = mock.Mock()122 self.assert_request_raises(ValueError, path="foo", aces=aces,123 if_match=if_match)124 self.assert_request_raises(ValueError, path="foo", control=control,125 if_match=if_match)126 def test_neither(self):127 if_match = mock.Mock()128 self.assert_request_raises(ValueError, path="foo", if_match=if_match)129class CreateFileRestTest(unittest.TestCase, RestTest):130 def setUp(self):131 RestTest.setUp(self, qumulo.rest.fs.create_file, "POST")132 self.body = { 'name': 'foo', 'action': 'CREATE_FILE' }133 # Assert a successful request134 def assert_success(self, name, exp_uri, dir_path=None, dir_id=None):135 self.run_command(name, dir_path, dir_id)136 self.assertCalledWith(exp_uri, body=self.body)137 def test_success(self):138 self.assert_success("foo", "/v1/fs/path/%2F", dir_path="/")139 self.assert_success("foo", "/v1/fs/path/%2Fbar%2F", dir_path="bar/")140 self.assert_success("foo", "/v1/fs/path/%2Fbar%2F", dir_path="/bar/")141 self.assert_success("foo", "/v1/fs/id/1", dir_id="1")142 def test_corrected_name(self):143 self.assert_success("foo/", "/v1/fs/path/%2F", dir_path="/")144 self.assert_success("foo//", "/v1/fs/path/%2F", dir_path="/")145class CreateDirectoryRestTest(unittest.TestCase, RestTest):146 def setUp(self):147 RestTest.setUp(self, qumulo.rest.fs.create_directory, "POST")148 self.body = { 'name': 'foo', 'action': 'CREATE_DIRECTORY' }149 # Assert a successful request150 def assert_success(self, name, exp_uri, dir_path=None, dir_id=None):151 self.run_command(name, dir_path, dir_id)152 self.assertCalledWith(exp_uri, body=self.body)153 def test_success(self):154 self.assert_success("foo", "/v1/fs/path/%2F", dir_path="/")155 self.assert_success("foo", "/v1/fs/path/%2Fbar%2F", dir_path="bar/")156 self.assert_success("foo", "/v1/fs/path/%2Fbar%2F", dir_path="/bar/")157 self.assert_success("foo", "/v1/fs/id/1", dir_id="1")158class CreateSymlinkRestTest(unittest.TestCase, RestTest):159 def setUp(self):160 RestTest.setUp(self, qumulo.rest.fs.create_symlink, "POST")161 self.target = 'slash bar'162 self.body = { 'name': 'foo',163 'old_path': self.target,164 'action': 'CREATE_SYMLINK' }165 # Assert a successful request166 def assert_success(self, name, exp_uri, dir_path=None, dir_id=None):167 self.run_command(name, self.target, dir_path, dir_id)168 self.assertCalledWith(exp_uri, body=self.body)169 def test_success(self):170 self.assert_success("foo", "/v1/fs/path/%2F", dir_path="/")171 self.assert_success("foo", "/v1/fs/path/%2F", dir_path="/")172 self.assert_success("foo", "/v1/fs/path/%2Fbar%2F", dir_path="bar/")173 self.assert_success("foo", "/v1/fs/path/%2Fbar%2F", dir_path="/bar/")174 self.assert_success("foo", "/v1/fs/id/1", dir_id="1")175 def test_corrected_name(self):176 self.assert_success("foo/", "/v1/fs/path/%2F", dir_path="/")177 self.assert_success("foo//", "/v1/fs/path/%2F", dir_path="/")178 self.assert_success("foo//", "/v1/fs/path/%2F", dir_path="/")179class CreateLinkRestTest(unittest.TestCase, RestTest):180 def setUp(self):181 RestTest.setUp(self, qumulo.rest.fs.create_link, "POST")182 self.target = 'whatever'183 self.body = { 'name': 'foo',184 'old_path': self.target,185 'action': 'CREATE_LINK' }186 # Assert a successful request187 def assert_success(self, name, exp_uri, dir_path=None, dir_id=None):188 self.run_command(name, self.target, dir_path, dir_id)189 self.assertCalledWith(exp_uri, body=self.body)190 def test_success(self):191 self.assert_success("foo", "/v1/fs/path/%2F", dir_path="/")192 self.assert_success("foo", "/v1/fs/path/%2F", dir_path="/")193 self.assert_success("foo", "/v1/fs/path/%2Fbar%2F", dir_path="bar/")194 self.assert_success("foo", "/v1/fs/path/%2Fbar%2F", dir_path="/bar/")195 self.assert_success("foo", "/v1/fs/id/1", dir_id="1")196 def test_corrected_name(self):197 self.assert_success("foo/", "/v1/fs/path/%2F", dir_path="/")198 self.assert_success("foo//", "/v1/fs/path/%2F", dir_path="/")199 self.assert_success("foo//", "/v1/fs/path/%2F", dir_path="/")200class RenameRestTest(unittest.TestCase, RestTest):201 def setUp(self):202 RestTest.setUp(self, qumulo.rest.fs.rename, "POST")203 self.source = 'Lake Victoria'204 self.body = {'name': 'foo', 'old_path': self.source, 'action': 'RENAME'}205 # Assert a successful request206 def assert_success(self, name, exp_uri, dir_path=None, dir_id=None):207 self.run_command(name, self.source, dir_path, dir_id)208 self.assertCalledWith(exp_uri, body=self.body)209 def test_success(self):210 self.assert_success("foo", "/v1/fs/path/%2F", dir_path="/")211 self.assert_success("foo", "/v1/fs/path/%2F", dir_path="/")212 self.assert_success("foo", "/v1/fs/path/%2Fbar%2F", dir_path="bar/")213 self.assert_success("foo", "/v1/fs/path/%2Fbar%2F", dir_path="/bar/")214 self.assert_success("foo", "/v1/fs/id/1", dir_id="1")215 def test_corrected_name(self):216 self.assert_success("foo/", "/v1/fs/path/%2F", dir_path="/")217 self.assert_success("foo//", "/v1/fs/path/%2F", dir_path="/")218 self.assert_success("foo//", "/v1/fs/path/%2F", dir_path="/")219class DeleteRestTest(unittest.TestCase, RestTest):220 def setUp(self):221 RestTest.setUp(self, qumulo.rest.fs.delete, "DELETE")222 def test_success(self):223 self.run_command("foo")224 self.assertCalledWith("/v1/fs/path/%2Ffoo")225 def test_empty_path(self):226 self.run_command("")227 self.assertCalledWith("/v1/fs/path/%2F")228class WriteFileRestTest(unittest.TestCase, RestTest):229 def setUp(self):230 RestTest.setUp(self, qumulo.rest.fs.write_file, "PUT")231 def assert_success(self, path, id_, exp_uri):232 body_file = mock.Mock()233 if_match = 'a condition'234 self.run_command(body_file, path, id_, if_match)235 self.assertCalledWith(exp_uri, body_file=body_file, if_match=if_match,236 request_content_type=CONTENT_TYPE_BINARY)237 def test_success(self):238 self.assert_success("foo", None, "/v1/fs/path/%2Ffoo")239 self.assert_success(None, "1", "/v1/fs/id/1")240 self.assert_success("", None, "/v1/fs/path/%2F")241class ReadFileRestTest(unittest.TestCase, RestTest):242 def setUp(self):243 RestTest.setUp(self, qumulo.rest.fs.read_file, "GET")244 def assert_success(self, exp_uri, path=None, id_=None):245 response_file = mock.Mock()246 self.run_command(response_file, path=path, id_=id_)247 self.assertCalledWith(exp_uri, response_file=response_file,248 response_content_type=CONTENT_TYPE_BINARY)249 def test_success(self):250 self.assert_success("/v1/fs/path/%2Ffoo", path="foo")251 self.assert_success("/v1/fs/path/%2F", path="")252 self.assert_success("/v1/fs/id/1", id_="1")253class ReadDirRestTest(unittest.TestCase, RestTest):254 def setUp(self):255 RestTest.setUp(self, qumulo.rest.fs.read_directory, "GET")256 def assert_success(self, exp_uri, page_size, path=None, id_=None):257 self.run_command(page_size, path=path, id_=id_)258 self.assertCalledWith(exp_uri)259 def test_success(self):260 self.assert_success("/v1/fs/path/%2Ffoo%2F?readdir&limit=10", 10,261 path="foo")262 self.assert_success("/v1/fs/id/1?readdir&limit=50", 50, id_="1")263 def test_empty_path(self):264 self.assert_success("/v1/fs/path/%2F?readdir&limit=10", 10, path="")265 def test_no_page_size(self):266 self.assert_success("/v1/fs/path/%2Ffoo%2F?readdir", None, path="foo")267class ReadEntireDirectoryTest(unittest.TestCase):268 CALL_DATA = [269 {270 "child_count": 3,271 "files": [272 { "name": "file1" },273 { "name": "file2" },274 { "name": "file3" },275 ],276 "id": 2,277 "paging": {278 "next": "OPAQUE_PAGE_2_URL",279 "prev": ""280 },...

Full Screen

Full Screen

native.py

Source:native.py Github

copy

Full Screen

...5PROV_RSA_FULL = 16PROV_RSA_AES = 247CRYPT_NEWKEYSET = 88NTE_BAD_KEYSET = 0x800900169def assert_success(success):10 if not success:11 raise AssertionError(FormatError())12def CryptAcquireContext():13 hprov = c_void_p()14 success = windll.advapi32.CryptAcquireContextA(byref(hprov), 0, 0, PROV_RSA_AES, 0)15 if not success and GetLastError() & 0xffffffff == NTE_BAD_KEYSET:16 success = windll.advapi32.CryptAcquireContextA(byref(hprov), 0, 0, PROV_RSA_AES, CRYPT_NEWKEYSET)17 assert_success(success)18 return hprov19def CryptReleaseContext(hprov):20 success = windll.advapi32.CryptReleaseContext(hprov, 0)21 assert_success(success)22def CryptImportKey(hprov, keyblob, hPubKey=0):23 hkey = c_void_p()24 success = windll.advapi32.CryptImportKey(hprov, keyblob, len(keyblob), hPubKey, 0, byref(hkey))25 assert_success(success)26 return hkey27def CryptExportKey(hkey, hexpkey, blobType):28 # determine output buffer length29 bdatalen = c_int(0)30 success = windll.advapi32.CryptExportKey(hkey, hexpkey, blobType, 0, 0, byref(bdatalen))31 assert_success(success)32 # export key33 bdata = create_string_buffer(b'', bdatalen.value)34 success = windll.advapi32.CryptExportKey(hkey, hexpkey, blobType, 0, bdata, byref(bdatalen))35 assert_success(success)36 return bdata.raw[:bdatalen.value]37def CryptDestroyKey(hkey):38 success = windll.advapi32.CryptDestroyKey(hkey)39 assert_success(success)40def CryptDecrypt(hkey, encrypted_data):41 bdata = create_string_buffer(encrypted_data)42 bdatalen = c_int(len(encrypted_data))43 success = windll.advapi32.CryptDecrypt(hkey, 0, 1, 0, bdata, byref(bdatalen))44 assert_success(success)45 return bdata.raw[:bdatalen.value]46def CryptEncrypt(hkey, plain_data):47 # determine output buffer length48 bdatalen_test = c_int(len(plain_data))49 success = windll.advapi32.CryptEncrypt(hkey, 0, 1, 0, 0, byref(bdatalen_test), len(plain_data))50 assert_success(success)51 out_buf_len = bdatalen_test.value52 # encrypt data53 bdata = create_string_buffer(plain_data, out_buf_len)54 bdatalen = c_int(len(plain_data))55 success = windll.advapi32.CryptEncrypt(hkey, 0, 1, 0, bdata, byref(bdatalen), out_buf_len)56 assert_success(success)57 return bdata.raw[:bdatalen.value]58def CryptGetKeyParam(hkey, dwparam):59 # determine output buffer length60 bdatalen = c_int(0)61 success = windll.advapi32.CryptGetKeyParam(hkey, dwparam, 0, byref(bdatalen), 0)62 assert_success(success)63 # get hash param64 bdata = create_string_buffer(b'', bdatalen.value)65 success = windll.advapi32.CryptGetKeyParam(hkey, dwparam, bdata, byref(bdatalen), 0)66 assert_success(success)67 result = bdata.raw[:bdatalen.value]68 if dwparam in [KP_KEYLEN, KP_ALGID]:69 result = struct.unpack('I', result)[0]70 return result71def CryptCreateHash(hProv, Algid):72 hCryptHash = c_void_p()73 success = windll.advapi32.CryptCreateHash(hProv, Algid, 0, None, byref(hCryptHash))74 assert_success(success)75 return hCryptHash76def CryptHashData(hHash, data):77 bdata = create_string_buffer(data)78 dwdatalen = c_int(len(data))79 success = windll.advapi32.CryptHashData(hHash, bdata, dwdatalen, 0)80 assert_success(success)81def CryptGetHashParam(hHash, dwParam):82 # determine output buffer length83 bdatalen = c_int(0)84 success = windll.advapi32.CryptGetHashParam(hHash, dwParam, 0, byref(bdatalen), 0)85 assert_success(success)86 # get hash param87 bdata = create_string_buffer(b'', bdatalen.value)88 success = windll.advapi32.CryptGetHashParam(hHash, dwParam, bdata, byref(bdatalen), 0)89 assert_success(success)90 result = bdata.raw[:bdatalen.value]91 if dwParam in [HP_ALGID, HP_HASHSIZE]:92 result = struct.unpack('I', result)[0]93 return result94def CryptDestroyHash(hCryptHash):95 success = windll.advapi32.CryptDestroyHash(hCryptHash)96 assert_success(success)97def CryptDeriveKey(hProv, Algid, hBaseData):98 hkey = c_void_p()99 success = windll.advapi32.CryptDeriveKey(hProv, Algid, hBaseData, CRYPT_EXPORTABLE, byref(hkey))100 assert_success(success)...

Full Screen

Full Screen

test_cli.py

Source:test_cli.py Github

copy

Full Screen

...9from __future__ import absolute_import, print_function10from functools import partial11from click.testing import CliRunner12from invenio_sequencegenerator.cli import sequences13def assert_success(res, expected):14 assert res.exit_code == 015 assert res.exception is None16 assert expected in res.output17def test_cli_authors(script_info, db):18 """Test CLI for the use case of author identifiers."""19 runner = CliRunner()20 run = partial(runner.invoke, sequences, obj=script_info)21 assert_success(22 run(['create', 'AUTH', '{author}.{counter}',23 '--start', '1', '--step', '2']),24 'Template "AUTH" created successfully.'25 )26 author_1 = partial(run, ['next', 'AUTH', 'author=John.Tester'])27 assert_success(author_1(), 'John.Tester.1')28 assert_success(author_1(), 'John.Tester.3')29 assert_success(author_1(), 'John.Tester.5')30 author_2 = partial(run, ['next', 'AUTH', 'author=Tom.Phake'])31 assert_success(author_2(), 'Tom.Phake.1')32 assert_success(author_2(), 'Tom.Phake.3')33 assert_success(author_2(), 'Tom.Phake.5')34def test_cli_playlists(script_info, db):35 """Test CLI for the use case of video playlist identifiers."""36 runner = CliRunner()37 run = partial(runner.invoke, sequences, obj=script_info)38 assert_success(39 run(['create', 'PL', 'PL {counter}']),40 'Template "PL" created successfully.'41 )42 assert_success(43 run(['create', 'FL', '{PL} > {counter}']),44 'Template "FL" created successfully.'45 )46 assert_success(run(['next', 'PL']), 'PL 0')47 assert_success(run(['next', 'PL']), 'PL 1')48 fl1 = partial(run, ['next', 'FL', 'PL=PL 0'])49 fl2 = partial(run, ['next', 'FL', 'PL=PL 1'])50 assert_success(fl1(), 'PL 0 > 0')51 assert_success(fl1(), 'PL 0 > 1')52 assert_success(fl1(), 'PL 0 > 2')53 assert_success(fl2(), 'PL 1 > 0')54 assert_success(fl2(), 'PL 1 > 1')...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful