How to use type_checker method in hypothesis

Best Python code snippet using hypothesis

demo_deepcoder_enumerator.py

Source:demo_deepcoder_enumerator.py Github

copy

Full Screen

...14 types.FunctionType,15 types.LambdaType,16 types.MethodType,17])18def type_checker(actual, expect):19 na = len(actual)20 ne = len(expect)21 if na!=ne:22 return False23 for i in range(na):24 if type(expect[i])==set:25 # need to match anyone26 # so in this DSL, the "set" type is not avaiable27 # since it's used here as special type28 if not actual[i] in expect[i]:29 return False30 elif actual[i]!=expect[i]:31 # need to match exactly32 return False33 return True34class DeepCoderInterpreter(PostOrderInterpreter):35 def eval_fn_pool(self, v):36 # no exception handler37 fn_dict = {38 "pos": self.eval_pos,39 "neg": self.eval_neg,40 "plus": self.eval_plus,41 "minus": self.eval_minus,42 "mul": self.eval_mul,43 "div": self.eval_div,44 "pow": self.eval_pow,45 "gt_zero": self.eval_gt_zero,46 "lt_zero": self.eval_lt_zero,47 "is_even": self.eval_is_even,48 "is_odd": self.eval_is_odd,49 }50 if v in fn_dict:51 return fn_dict[v]52 else:53 raise GeneralError()54 def eval_mfn_pool(self, v):55 # no exception handler56 fn_dict = {57 "plus": self.meta_plus,58 "minus": self.meta_minus,59 "mul": self.meta_mul,60 "div": self.meta_div,61 "pow": self.meta_pow,62 }63 if v in fn_dict:64 return fn_dict[v]65 else:66 raise GeneralError()67 def eval_int_pool(self, v):68 return int(v)69 def eval_get_fn(self, node, args):70 return args[0]71 def eval_get_int(self, node, args):72 return args[0]73 def eval_get_mfn(self, node, args):74 if type_checker([type(d) for d in args], [function_types, int]):75 return args[0](args[1])76 else:77 raise GeneralError()78 def eval_head(self, node, args):79 if type_checker([type(d) for d in args], [list]):80 if len(args[0])>0:81 return args[0][0]82 else:83 raise GeneralError()84 else:85 raise GeneralError()86 def eval_last(self, node, args):87 if type_checker([type(d) for d in args], [list]):88 if len(args[0])>0:89 return args[0][-1]90 else:91 raise GeneralError()92 else:93 raise GeneralError()94 def eval_take(self, node, args):95 if type_checker([type(d) for d in args], [int, list]):96 if len(args[1])<=args[0]:97 return args[1]98 else:99 return args[1][:args[0]]100 else:101 raise GeneralError()102 def eval_drop(self, node, args):103 if type_checker([type(d) for d in args], [int, list]):104 if len(args[1])<=args[0]:105 return []106 else:107 return args[1][args[0]:]108 else:109 raise GeneralError()110 def eval_access(self, node, args):111 if type_checker([type(d) for d in args], [int, list]):112 if args[0]<len(args[1]) and args[0]>=0:113 return args[1][args[0]]114 else:115 raise GeneralError()116 else:117 raise GeneralError()118 def eval_minimum(self, node, args):119 if type_checker([type(d) for d in args], [list]):120 if len(args[0])>0:121 return min(args[0])122 else:123 raise GeneralError()124 else:125 raise GeneralError()126 def eval_maximum(self, node, args):127 if type_checker([type(d) for d in args], [list]):128 if len(args[0])>0:129 return max(args[0])130 else:131 raise GeneralError()132 else:133 raise GeneralError()134 def eval_reverse(self, node, args):135 if type_checker([type(d) for d in args], [list]):136 return args[0][::-1]137 else:138 raise GeneralError()139 def eval_sort(self, node, args):140 if type_checker([type(d) for d in args], [list]):141 return sorted(args[0])142 else:143 raise GeneralError()144 def eval_sum(self, node, args):145 if type_checker([type(d) for d in args], [list]):146 return sum(args[0])147 else:148 raise GeneralError()149 def eval_map(self, node, args):150 # call like "fn( [args] )"151 if type_checker([type(d) for d in args], [function_types, list]):152 return [args[0]( node, [d_item] ) for d_item in args[1]]153 else:154 raise GeneralError()155 def eval_filter(self, node, args):156 # call like "fn( [args] )"157 if type_checker([type(d) for d in args], [function_types, list]):158 rel = []159 for d_item in args[1]:160 if args[0]( node, [d_item] ):161 rel.append(d_item)162 return rel163 else:164 raise GeneralError()165 def eval_count(self, node, args):166 # call like "fn( [args] )"167 if type_checker([type(d) for d in args], [function_types, list]):168 rel = []169 for d_item in args[1]:170 if args[0]( node, [d_item] ):171 rel.append(d_item)172 return len(rel)173 else:174 raise GeneralError()175 def eval_zipwith(self, node, args):176 # call like "fn( [args] )"177 if type_checker([type(d) for d in args], [function_types, list, list]):178 return [args[0]( node, [x,y] ) for (x,y) in zip(args[1],args[2])]179 else:180 raise GeneralError()181 def eval_scanl1(self, node, args):182 # call like "fn( [args] )"183 if type_checker([type(d) for d in args], [function_types, list]):184 rel = []185 if len(args[1])>0:186 rel.append(args[1][0])187 for i in range(1, len(args[1])):188 rel.append( args[0]( node, [rel[i-1],args[1][i]] ) )189 return rel190 else:191 raise GeneralError()192 def eval_pos(self, node, args):193 if type_checker([type(d) for d in args], [int]):194 return args[0]195 else:196 raise GeneralError()197 def eval_neg(self, node, args):198 if type_checker([type(d) for d in args], [int]):199 return -args[0]200 else:201 raise GeneralError()202 def eval_plus(self, node, args):203 if type_checker([type(d) for d in args], [int, int]):204 return args[0]+args[1]205 else:206 raise GeneralError()207 def eval_minus(self, node, args):208 if type_checker([type(d) for d in args], [int, int]):209 return args[0]-args[1]210 else:211 raise GeneralError()212 def eval_mul(self, node, args):213 if type_checker([type(d) for d in args], [int, int]):214 return args[0]*args[1]215 else:216 raise GeneralError()217 def eval_div(self, node, args):218 if type_checker([type(d) for d in args], [int, int]):219 if args[1]==0:220 raise GeneralError()221 return args[0]//args[1] # truncated version to keep the results in int range222 else:223 raise GeneralError()224 def eval_pow(self, node, args):225 if type_checker([type(d) for d in args], [int, int]):226 if args[1]<0: # do not deal with power<0227 raise GeneralError()228 if args[0]<=0: # do not deal with base<=0229 raise GeneralError() 230 return args[0]**args[1]231 else:232 raise GeneralError()233 def eval_gt_zero(self, node, args):234 if type_checker([type(d) for d in args], [int]):235 return args[0]>0236 else:237 raise GeneralError()238 def eval_lt_zero(self, node, args):239 if type_checker([type(d) for d in args], [int]):240 return args[0]<0241 else:242 raise GeneralError()243 def eval_is_even(self, node, args):244 if type_checker([type(d) for d in args], [int]):245 return args[0]%2==0246 else:247 raise GeneralError()248 def eval_is_odd(self, node, args):249 if type_checker([type(d) for d in args], [int]):250 return args[0]%2!=0251 else:252 raise GeneralError()253 # ### meta function ### #254 def meta_plus(self, p):255 def fn_plus(node, args):256 if type_checker([type(d) for d in args], [int]):257 return args[0]+p258 else:259 raise GeneralError()260 return fn_plus261 # ### meta function ### #262 def meta_minus(self, p):263 def fn_minus(node, args):264 if type_checker([type(d) for d in args], [int]):265 return args[0]-p266 else:267 raise GeneralError()268 return fn_minus269 # ### meta function ### #270 def meta_mul(self, p):271 def fn_mul(node, args):272 if type_checker([type(d) for d in args], [int]):273 return args[0]*p274 else:275 raise GeneralError()276 return fn_mul277 # ### meta function ### #278 def meta_div(self, p):279 def fn_div(node, args):280 if type_checker([type(d) for d in args], [int]):281 if p==0:282 raise GeneralError()283 return args[0]//p # truncated version to keep the results in int range284 else:285 raise GeneralError()286 return fn_div287 # ### meta function ### #288 def meta_pow(self, p):289 def fn_pow(node, args):290 if type_checker([type(d) for d in args], [int]):291 if p<0: # do not deal with power<0292 raise GeneralError()293 if args[0]<=0: # do not deal with base<=0294 raise GeneralError()295 return args[0]**p296 else:297 raise GeneralError()298 return fn_pow299def main():300 logger.info('Parsing Spec...')301 spec = S.parse_file('example/deepcoder.tyrell')302 logger.info('Parsing succeeded')303 logger.info('Building synthesizer...')304 synthesizer = Synthesizer(...

Full Screen

Full Screen

test_types.py

Source:test_types.py Github

copy

Full Screen

1"""2Tests on the new type interface. The actual correctness of the type checking3is handled in test_jsonschema_test_suite; these tests check that TypeChecker4functions correctly and can facilitate extensions to type checking5"""6from collections import namedtuple7from unittest import TestCase8from jsonschema import ValidationError, _validators9from jsonschema._types import TypeChecker10from jsonschema.exceptions import UndefinedTypeCheck11from jsonschema.validators import Draft4Validator, extend12def equals_2(checker, instance):13 return instance == 214def is_namedtuple(instance):15 return isinstance(instance, tuple) and getattr(instance, "_fields", None)16def is_object_or_named_tuple(checker, instance):17 if Draft4Validator.TYPE_CHECKER.is_type(instance, "object"):18 return True19 return is_namedtuple(instance)20def coerce_named_tuple(fn):21 def coerced(validator, value, instance, schema):22 if is_namedtuple(instance):23 instance = instance._asdict()24 return fn(validator, value, instance, schema)25 return coerced26required = coerce_named_tuple(_validators.required)27properties = coerce_named_tuple(_validators.properties)28class TestTypeChecker(TestCase):29 def test_is_type(self):30 checker = TypeChecker({"two": equals_2})31 self.assertEqual(32 (33 checker.is_type(instance=2, type="two"),34 checker.is_type(instance="bar", type="two"),35 ),36 (True, False),37 )38 def test_is_unknown_type(self):39 with self.assertRaises(UndefinedTypeCheck) as context:40 TypeChecker().is_type(4, "foobar")41 self.assertIn("foobar", str(context.exception))42 def test_checks_can_be_added_at_init(self):43 checker = TypeChecker({"two": equals_2})44 self.assertEqual(checker, TypeChecker().redefine("two", equals_2))45 def test_redefine_existing_type(self):46 self.assertEqual(47 TypeChecker().redefine("two", object()).redefine("two", equals_2),48 TypeChecker().redefine("two", equals_2),49 )50 def test_remove(self):51 self.assertEqual(52 TypeChecker({"two": equals_2}).remove("two"),53 TypeChecker(),54 )55 def test_remove_unknown_type(self):56 with self.assertRaises(UndefinedTypeCheck) as context:57 TypeChecker().remove("foobar")58 self.assertIn("foobar", str(context.exception))59 def test_redefine_many(self):60 self.assertEqual(61 TypeChecker().redefine_many({"foo": int, "bar": str}),62 TypeChecker().redefine("foo", int).redefine("bar", str),63 )64 def test_remove_multiple(self):65 self.assertEqual(66 TypeChecker({"foo": int, "bar": str}).remove("foo", "bar"),67 TypeChecker(),68 )69 def test_type_check_can_raise_key_error(self):70 """71 Make sure no one writes:72 try:73 self._type_checkers[type](...)74 except KeyError:75 ignoring the fact that the function itself can raise that.76 """77 error = KeyError("Stuff")78 def raises_keyerror(checker, instance):79 raise error80 with self.assertRaises(KeyError) as context:81 TypeChecker({"foo": raises_keyerror}).is_type(4, "foo")82 self.assertIs(context.exception, error)83class TestCustomTypes(TestCase):84 def test_simple_type_can_be_extended(self):85 def int_or_str_int(checker, instance):86 if not isinstance(instance, (int, str)):87 return False88 try:89 int(instance)90 except ValueError:91 return False92 return True93 CustomValidator = extend(94 Draft4Validator,95 type_checker=Draft4Validator.TYPE_CHECKER.redefine(96 "integer", int_or_str_int,97 ),98 )99 validator = CustomValidator({"type": "integer"})100 validator.validate(4)101 validator.validate("4")102 with self.assertRaises(ValidationError):103 validator.validate(4.4)104 def test_object_can_be_extended(self):105 schema = {"type": "object"}106 Point = namedtuple("Point", ["x", "y"])107 type_checker = Draft4Validator.TYPE_CHECKER.redefine(108 u"object", is_object_or_named_tuple,109 )110 CustomValidator = extend(Draft4Validator, type_checker=type_checker)111 validator = CustomValidator(schema)112 validator.validate(Point(x=4, y=5))113 def test_object_extensions_require_custom_validators(self):114 schema = {"type": "object", "required": ["x"]}115 type_checker = Draft4Validator.TYPE_CHECKER.redefine(116 u"object", is_object_or_named_tuple,117 )118 CustomValidator = extend(Draft4Validator, type_checker=type_checker)119 validator = CustomValidator(schema)120 Point = namedtuple("Point", ["x", "y"])121 # Cannot handle required122 with self.assertRaises(ValidationError):123 validator.validate(Point(x=4, y=5))124 def test_object_extensions_can_handle_custom_validators(self):125 schema = {126 "type": "object",127 "required": ["x"],128 "properties": {"x": {"type": "integer"}},129 }130 type_checker = Draft4Validator.TYPE_CHECKER.redefine(131 u"object", is_object_or_named_tuple,132 )133 CustomValidator = extend(134 Draft4Validator,135 type_checker=type_checker,136 validators={"required": required, "properties": properties},137 )138 validator = CustomValidator(schema)139 Point = namedtuple("Point", ["x", "y"])140 # Can now process required and properties141 validator.validate(Point(x=4, y=5))142 with self.assertRaises(ValidationError):...

Full Screen

Full Screen

mixture.py

Source:mixture.py Github

copy

Full Screen

...61 print("\nRULE",self)62 print('\tTURN',mixture)63 print('\tINTO',out)64 return out65 def set_type_checker(self,type_checker):66 self.type_checker = type_checker67class ReductionRuleComponentAsMixture:68 'Just wraps a ReductionRuleComponent, but has an apply method operates on mixtures'69 def __init__(self, component_rule):70 self.component_rule = component_rule71 def apply(self,mixture,debug=False):72 return Mixture([self.component_rule.apply(c,debug) for c in mixture.components])73 def set_type_checker(self, type_checker):74 self.component_rule.type_checker = type_checker75 def __str__(self):76 return str(self.component_rule)77def match_mixture_pattern(pattern_components,components,type_checker,partial_match={}):78 """79 pattern_components is a list of ComponentRuleLHS, probably consisting of some variables80 components is a list of Components, probably consisnting of only constants81 type_checker is a TypeChecker82 partial_match helps with recursion, ignore for normal usage83 Returns None if there is no match. If there is a match then it returns a pair consisting of:84 (1) a dict mapping modifier and ingredient variables to the constants showing up in components85 (2) a list of components that were not involved in the match86 """87 if not pattern_components:...

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 hypothesis 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